PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/backwpup/vendor/OpenCloud/Common/Base.php

https://gitlab.com/pankajmohale/chef2go
PHP | 430 lines | 229 code | 48 blank | 153 comment | 34 complexity | 2de850fdb156fab6e03d976ce04159ad MD5 | raw file
  1. <?php
  2. /**
  3. * Copyright 2012-2014 Rackspace US, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace OpenCloud\Common;
  18. use OpenCloud\Common\Collection\ResourceIterator;
  19. use OpenCloud\Common\Constants\Header as HeaderConst;
  20. use OpenCloud\Common\Constants\Mime as MimeConst;
  21. use OpenCloud\Common\Exceptions\JsonError;
  22. use Psr\Log\LoggerInterface;
  23. /**
  24. * The root class for all other objects used or defined by this SDK.
  25. *
  26. * It contains common code for error handling as well as service functions that
  27. * are useful. Because it is an abstract class, it cannot be called directly,
  28. * and it has no publicly-visible properties.
  29. */
  30. abstract class Base
  31. {
  32. /**
  33. * Holds all the properties added by overloading.
  34. *
  35. * @var array
  36. */
  37. private $properties = array();
  38. /**
  39. * The logger instance
  40. *
  41. * @var LoggerInterface
  42. */
  43. private $logger;
  44. /**
  45. * The aliases configure for the properties of the instance.
  46. *
  47. * @var array
  48. */
  49. protected $aliases = array();
  50. /**
  51. * @return static
  52. */
  53. public static function getInstance()
  54. {
  55. return new static();
  56. }
  57. /**
  58. * Intercept non-existent method calls for dynamic getter/setter functionality.
  59. *
  60. * @param $method
  61. * @param $args
  62. * @throws Exceptions\RuntimeException
  63. */
  64. public function __call($method, $args)
  65. {
  66. $prefix = substr($method, 0, 3);
  67. // Get property - convert from camel case to underscore
  68. $property = lcfirst(substr($method, 3));
  69. // Only do these methods on properties which exist
  70. if ($this->propertyExists($property) && $prefix == 'get') {
  71. return $this->getProperty($property);
  72. }
  73. // Do setter
  74. if ($this->propertyExists($property) && $prefix == 'set') {
  75. return $this->setProperty($property, $args[0]);
  76. }
  77. throw new Exceptions\RuntimeException(sprintf(
  78. 'No method %s::%s()',
  79. get_class($this),
  80. $method
  81. ));
  82. }
  83. /**
  84. * We can set a property under three conditions:
  85. *
  86. * 1. If it has a concrete setter: setProperty()
  87. * 2. If the property exists
  88. * 3. If the property name's prefix is in an approved list
  89. *
  90. * @param mixed $property
  91. * @param mixed $value
  92. * @return mixed
  93. */
  94. protected function setProperty($property, $value)
  95. {
  96. $setter = 'set' . $this->toCamel($property);
  97. if (method_exists($this, $setter)) {
  98. return call_user_func(array($this, $setter), $value);
  99. } elseif (false !== ($propertyVal = $this->propertyExists($property))) {
  100. // Are we setting a public or private property?
  101. if ($this->isAccessible($propertyVal)) {
  102. $this->$propertyVal = $value;
  103. } else {
  104. $this->properties[$propertyVal] = $value;
  105. }
  106. return $this;
  107. } else {
  108. $this->getLogger()->warning(
  109. 'Attempted to set {property} with value {value}, but the'
  110. . ' property has not been defined. Please define first.',
  111. array(
  112. 'property' => $property,
  113. 'value' => print_r($value, true)
  114. )
  115. );
  116. }
  117. }
  118. /**
  119. * Basic check to see whether property exists.
  120. *
  121. * @param string $property The property name being investigated.
  122. * @param bool $allowRetry If set to TRUE, the check will try to format the name in underscores because
  123. * there are sometimes discrepancies between camelCaseNames and underscore_names.
  124. * @return bool
  125. */
  126. protected function propertyExists($property, $allowRetry = true)
  127. {
  128. if (!property_exists($this, $property) && !$this->checkAttributePrefix($property)) {
  129. // Convert to under_score and retry
  130. if ($allowRetry) {
  131. return $this->propertyExists($this->toUnderscores($property), false);
  132. } else {
  133. $property = false;
  134. }
  135. }
  136. return $property;
  137. }
  138. /**
  139. * Convert a string to camelCase format.
  140. *
  141. * @param $string
  142. * @param bool $capitalise Optional flag which allows for word capitalization.
  143. * @return mixed
  144. */
  145. public function toCamel($string, $capitalise = true)
  146. {
  147. if ($capitalise) {
  148. $string = ucfirst($string);
  149. }
  150. return preg_replace_callback('/_([a-z])/', function ($char) {
  151. return strtoupper($char[1]);
  152. }, $string);
  153. }
  154. /**
  155. * Convert string to underscore format.
  156. *
  157. * @param $string
  158. * @return mixed
  159. */
  160. public function toUnderscores($string)
  161. {
  162. $string = lcfirst($string);
  163. return preg_replace_callback('/([A-Z])/', function ($char) {
  164. return "_" . strtolower($char[1]);
  165. }, $string);
  166. }
  167. /**
  168. * Does the property exist in the object variable list (i.e. does it have public or protected visibility?)
  169. *
  170. * @param $property
  171. * @return bool
  172. */
  173. private function isAccessible($property)
  174. {
  175. return array_key_exists($property, get_object_vars($this));
  176. }
  177. /**
  178. * Checks the attribute $property and only permits it if the prefix is
  179. * in the specified $prefixes array
  180. *
  181. * This is to support extension namespaces in some services.
  182. *
  183. * @param string $property the name of the attribute
  184. * @return boolean
  185. */
  186. private function checkAttributePrefix($property)
  187. {
  188. if (!method_exists($this, 'getService')) {
  189. return false;
  190. }
  191. $prefix = strstr($property, ':', true);
  192. return in_array($prefix, $this->getService()->namespaces());
  193. }
  194. /**
  195. * Grab value out of the data array.
  196. *
  197. * @param string $property
  198. * @return mixed
  199. */
  200. protected function getProperty($property)
  201. {
  202. if (array_key_exists($property, $this->properties)) {
  203. return $this->properties[$property];
  204. } elseif (array_key_exists($this->toUnderscores($property), $this->properties)) {
  205. return $this->properties[$this->toUnderscores($property)];
  206. } elseif (method_exists($this, 'get' . ucfirst($property))) {
  207. return call_user_func(array($this, 'get' . ucfirst($property)));
  208. } elseif (false !== ($propertyVal = $this->propertyExists($property)) && $this->isAccessible($propertyVal)) {
  209. return $this->$propertyVal;
  210. }
  211. return null;
  212. }
  213. /**
  214. * Sets the logger.
  215. *
  216. * @param LoggerInterface $logger
  217. *
  218. * @return $this
  219. */
  220. public function setLogger(LoggerInterface $logger = null)
  221. {
  222. $this->logger = $logger;
  223. return $this;
  224. }
  225. /**
  226. * Returns the Logger object.
  227. *
  228. * @return LoggerInterface
  229. */
  230. public function getLogger()
  231. {
  232. if (null === $this->logger) {
  233. $this->setLogger(new Log\Logger);
  234. }
  235. return $this->logger;
  236. }
  237. /**
  238. * @return bool
  239. */
  240. public function hasLogger()
  241. {
  242. return (null !== $this->logger);
  243. }
  244. /**
  245. * @deprecated
  246. */
  247. public function url($path = null, array $query = array())
  248. {
  249. return $this->getUrl($path, $query);
  250. }
  251. /**
  252. * Populates the current object based on an unknown data type.
  253. *
  254. * @param mixed $info
  255. * @param bool
  256. * @throws Exceptions\InvalidArgumentError
  257. */
  258. public function populate($info, $setObjects = true)
  259. {
  260. if (is_string($info) || is_integer($info)) {
  261. $this->setProperty($this->primaryKeyField(), $info);
  262. $this->refresh($info);
  263. } elseif (is_object($info) || is_array($info)) {
  264. foreach ($info as $key => $value) {
  265. if ($key == 'metadata' || $key == 'meta') {
  266. // Try retrieving existing value
  267. if (null === ($metadata = $this->getProperty($key))) {
  268. // If none exists, create new object
  269. $metadata = new Metadata;
  270. }
  271. // Set values for metadata
  272. $metadata->setArray($value);
  273. // Set object property
  274. $this->setProperty($key, $metadata);
  275. } elseif (!empty($this->associatedResources[$key]) && $setObjects === true) {
  276. // Associated resource
  277. try {
  278. $resource = $this->getService()->resource($this->associatedResources[$key], $value);
  279. $resource->setParent($this);
  280. $this->setProperty($key, $resource);
  281. } catch (Exception\ServiceException $e) {
  282. }
  283. } elseif (!empty($this->associatedCollections[$key]) && $setObjects === true) {
  284. // Associated collection
  285. try {
  286. $className = $this->associatedCollections[$key];
  287. $options = $this->makeResourceIteratorOptions($className);
  288. $iterator = ResourceIterator::factory($this, $options, $value);
  289. $this->setProperty($key, $iterator);
  290. } catch (Exception\ServiceException $e) {
  291. }
  292. } elseif (!empty($this->aliases[$key])) {
  293. // Sometimes we might want to preserve camelCase
  294. // or covert `rax-bandwidth:bandwidth` to `raxBandwidth`
  295. $this->setProperty($this->aliases[$key], $value);
  296. } else {
  297. // Normal key/value pair
  298. $this->setProperty($key, $value);
  299. }
  300. }
  301. } elseif (null !== $info) {
  302. throw new Exceptions\InvalidArgumentError(sprintf(
  303. Lang::translate('Argument for [%s] must be string or object'),
  304. get_class()
  305. ));
  306. }
  307. }
  308. /**
  309. * Checks the most recent JSON operation for errors.
  310. *
  311. * @throws Exceptions\JsonError
  312. * @codeCoverageIgnore
  313. */
  314. public static function checkJsonError()
  315. {
  316. switch (json_last_error()) {
  317. case JSON_ERROR_NONE:
  318. return;
  319. case JSON_ERROR_DEPTH:
  320. $jsonError = 'JSON error: The maximum stack depth has been exceeded';
  321. break;
  322. case JSON_ERROR_STATE_MISMATCH:
  323. $jsonError = 'JSON error: Invalid or malformed JSON';
  324. break;
  325. case JSON_ERROR_CTRL_CHAR:
  326. $jsonError = 'JSON error: Control character error, possibly incorrectly encoded';
  327. break;
  328. case JSON_ERROR_SYNTAX:
  329. $jsonError = 'JSON error: Syntax error';
  330. break;
  331. case JSON_ERROR_UTF8:
  332. $jsonError = 'JSON error: Malformed UTF-8 characters, possibly incorrectly encoded';
  333. break;
  334. default:
  335. $jsonError = 'Unexpected JSON error';
  336. break;
  337. }
  338. if (isset($jsonError)) {
  339. throw new JsonError(Lang::translate($jsonError));
  340. }
  341. }
  342. public static function generateUuid()
  343. {
  344. return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  345. // 32 bits for "time_low"
  346. mt_rand(0, 0xffff), mt_rand(0, 0xffff),
  347. // 16 bits for "time_mid"
  348. mt_rand(0, 0xffff),
  349. // 16 bits for "time_hi_and_version",
  350. // four most significant bits holds version number 4
  351. mt_rand(0, 0x0fff) | 0x4000,
  352. // 16 bits, 8 bits for "clk_seq_hi_res",
  353. // 8 bits for "clk_seq_low",
  354. // two most significant bits holds zero and one for variant DCE1.1
  355. mt_rand(0, 0x3fff) | 0x8000,
  356. // 48 bits for "node"
  357. mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
  358. );
  359. }
  360. public function makeResourceIteratorOptions($resource)
  361. {
  362. $options = array('resourceClass' => $this->stripNamespace($resource));
  363. if (method_exists($resource, 'jsonCollectionName')) {
  364. $options['key.collection'] = $resource::jsonCollectionName();
  365. }
  366. if (method_exists($resource, 'jsonCollectionElement')) {
  367. $options['key.collectionElement'] = $resource::jsonCollectionElement();
  368. }
  369. return $options;
  370. }
  371. public function stripNamespace($namespace)
  372. {
  373. $array = explode('\\', $namespace);
  374. return end($array);
  375. }
  376. protected static function getJsonHeader()
  377. {
  378. return array(HeaderConst::CONTENT_TYPE => MimeConst::JSON);
  379. }
  380. }