PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/codes-php/phpjakarta/WindowsAzure/Common/Internal/ServiceSettings.php

http://bukuphpjs.codeplex.com
PHP | 285 lines | 129 code | 30 blank | 126 comment | 15 complexity | 4a84ec6aca9a850b4049148c0d6b6249 MD5 | raw file
Possible License(s): Apache-2.0, MIT, LGPL-2.1
  1. <?php
  2. /**
  3. * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. *
  14. * PHP version 5
  15. *
  16. * @category Microsoft
  17. * @package WindowsAzure\Common\Internal
  18. * @author Azure PHP SDK <azurephpsdk@microsoft.com>
  19. * @copyright 2012 Microsoft Corporation
  20. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
  21. * @link https://github.com/windowsazure/azure-sdk-for-php
  22. */
  23. namespace WindowsAzure\Common\Internal;
  24. use WindowsAzure\Common\Internal\Resources;
  25. /**
  26. * Base class for all REST services settings.
  27. *
  28. * Derived classes must implement the following members:
  29. * 1- $isInitialized: A static property that indicates whether the class's static
  30. * members have been initialized.
  31. * 2- init(): A protected static method that initializes static members.
  32. * 3- $validSettingKeys: A static property that contains valid setting keys for this
  33. * service.
  34. * 4- createFromConnectionString($connectionString): A public static function that
  35. * takes a connection string and returns the created settings object.
  36. *
  37. * @category Microsoft
  38. * @package WindowsAzure\Common\Internal
  39. * @author Azure PHP SDK <azurephpsdk@microsoft.com>
  40. * @copyright 2012 Microsoft Corporation
  41. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
  42. * @version Release: @package_version@
  43. * @link https://github.com/windowsazure/azure-sdk-for-php
  44. */
  45. abstract class ServiceSettings
  46. {
  47. /**
  48. * Throws an exception if the connection string format does not match any of the
  49. * available formats.
  50. *
  51. * @param type $connectionString The invalid formatted connection string.
  52. *
  53. * @return none
  54. *
  55. * @throws \RuntimeException
  56. */
  57. protected static function noMatch($connectionString)
  58. {
  59. throw new \RuntimeException(
  60. sprintf(Resources::MISSING_CONNECTION_STRING_SETTINGS, $connectionString)
  61. );
  62. }
  63. /**
  64. * Parses the connection string and then validate that the parsed keys belong to
  65. * the $validSettingKeys
  66. *
  67. * @param string $connectionString The user provided connection string.
  68. *
  69. * @return array The tokenized connection string keys.
  70. *
  71. * @throws \RuntimeException
  72. */
  73. protected static function parseAndValidateKeys($connectionString)
  74. {
  75. // Initialize the static values if they are not initialized yet.
  76. if (!static::$isInitialized) {
  77. static::init();
  78. static::$isInitialized = true;
  79. }
  80. $tokenizedSettings = ConnectionStringParser::parseConnectionString(
  81. 'connectionString',
  82. $connectionString
  83. );
  84. // Assure that all given keys are valid.
  85. foreach ($tokenizedSettings as $key => $value) {
  86. if (!Utilities::inArrayInsensitive($key, static::$validSettingKeys) ) {
  87. throw new \RuntimeException(
  88. sprintf(
  89. Resources::INVALID_CONNECTION_STRING_SETTING_KEY,
  90. $key,
  91. implode("\n", static::$validSettingKeys)
  92. )
  93. );
  94. }
  95. }
  96. return $tokenizedSettings;
  97. }
  98. /**
  99. * Creates an anonymous function that acts as predicate.
  100. *
  101. * @param array $requirements The array of conditions to satisfy.
  102. * @param boolean $isRequired Either these conditions are all required or all
  103. * optional.
  104. * @param boolean $atLeastOne Indicates that at least one requirement must
  105. * succeed.
  106. *
  107. * @return callable
  108. */
  109. protected static function getValidator($requirements, $isRequired, $atLeastOne)
  110. {
  111. return function ($userSettings)
  112. use ($requirements, $isRequired, $atLeastOne)
  113. {
  114. $oneFound = false;
  115. $result = array_change_key_case($userSettings);
  116. foreach ($requirements as $requirement) {
  117. $settingName = strtolower($requirement[Resources::SETTING_NAME]);
  118. // Check if the setting name exists in the provided user settings.
  119. if (array_key_exists($settingName, $result)) {
  120. // Check if the provided user setting value is valid.
  121. $validationFunc = $requirement[Resources::SETTING_CONSTRAINT];
  122. $isValid = $validationFunc($result[$settingName]);
  123. if ($isValid) {
  124. // Remove the setting as indicator for successful validation.
  125. unset($result[$settingName]);
  126. $oneFound = true;
  127. }
  128. } else {
  129. // If required then fail because the setting does not exist
  130. if ($isRequired) {
  131. return null;
  132. }
  133. }
  134. }
  135. if ($atLeastOne) {
  136. // At least one requirement must succeed, otherwise fail.
  137. return $oneFound ? $result : null;
  138. } else {
  139. return $result;
  140. }
  141. };
  142. }
  143. /**
  144. * Creates at lease one succeed predicate for the provided list of requirements.
  145. *
  146. * @return callable
  147. */
  148. protected static function atLeastOne()
  149. {
  150. $allSettings = func_get_args();
  151. return self::getValidator($allSettings, false, true);
  152. }
  153. /**
  154. * Creates an optional predicate for the provided list of requirements.
  155. *
  156. * @return callable
  157. */
  158. protected static function optional()
  159. {
  160. $optionalSettings = func_get_args();
  161. return self::getValidator($optionalSettings, false, false);
  162. }
  163. /**
  164. * Creates an required predicate for the provided list of requirements.
  165. *
  166. * @return callable
  167. */
  168. protected static function allRequired()
  169. {
  170. $requiredSettings = func_get_args();
  171. return self::getValidator($requiredSettings, true, false);
  172. }
  173. /**
  174. * Creates a setting value condition using the passed predicate.
  175. *
  176. * @param string $name The setting key name.
  177. * @param callable $predicate The setting value predicate.
  178. *
  179. * @return array
  180. */
  181. protected static function settingWithFunc($name, $predicate)
  182. {
  183. $requirement = array();
  184. $requirement[Resources::SETTING_NAME] = $name;
  185. $requirement[Resources::SETTING_CONSTRAINT] = $predicate;
  186. return $requirement;
  187. }
  188. /**
  189. * Creates a setting value condition that validates it is one of the
  190. * passed valid values.
  191. *
  192. * @param string $name The setting key name.
  193. *
  194. * @return array
  195. */
  196. protected static function setting($name)
  197. {
  198. $validValues = func_get_args();
  199. // Remove $name argument.
  200. unset($validValues[0]);
  201. $validValuesCount = func_num_args();
  202. $predicate = function ($settingValue) use ($validValuesCount, $validValues)
  203. {
  204. if (empty($validValues)) {
  205. // No restrictions, succeed,
  206. return true;
  207. }
  208. // Check to find if the $settingValue is valid or not. The index must
  209. // start from 1 as unset deletes the value but does not update the array
  210. // indecies.
  211. for ($index = 1; $index < $validValuesCount; $index++) {
  212. if ($settingValue == $validValues[$index]) {
  213. // $settingValue is found in valid values set, succeed.
  214. return true;
  215. }
  216. }
  217. throw new \RuntimeException(
  218. sprintf(
  219. Resources::INVALID_CONFIG_VALUE,
  220. $settingValue,
  221. implode("\n", $validValues)
  222. )
  223. );
  224. // $settingValue is missing in valid values set, fail.
  225. return false;
  226. };
  227. return self::settingWithFunc($name, $predicate);
  228. }
  229. /**
  230. * Tests to see if a given list of settings matches a set of filters exactly.
  231. *
  232. * @param array $settings The settings to check.
  233. *
  234. * @return boolean If any filter returns null, false. If there are any settings
  235. * left over after all filters are processed, false. Otherwise true.
  236. */
  237. protected static function matchedSpecification($settings)
  238. {
  239. $constraints = func_get_args();
  240. // Remove first element which corresponds to $settings
  241. unset($constraints[0]);
  242. foreach ($constraints as $constraint) {
  243. $remainingSettings = $constraint($settings);
  244. if (is_null($remainingSettings)) {
  245. return false;
  246. } else {
  247. $settings = $remainingSettings;
  248. }
  249. }
  250. if (empty($settings)) {
  251. return true;
  252. }
  253. return false;
  254. }
  255. }