PageRenderTime 52ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/braintree/braintree_php/lib/Braintree/Util.php

https://gitlab.com/CORP-RESELLER/shopping-cart-lite
PHP | 303 lines | 188 code | 21 blank | 94 comment | 20 complexity | 166fd3bd13d07e90b1713fcd348b9d70 MD5 | raw file
  1. <?php
  2. /**
  3. * Braintree Utility methods
  4. * PHP version 5
  5. *
  6. * @copyright 2014 Braintree, a division of PayPal, Inc.
  7. */
  8. class Braintree_Util
  9. {
  10. /**
  11. * extracts an attribute and returns an array of objects
  12. *
  13. * extracts the requested element from an array, and converts the contents
  14. * of its child arrays to objects of type Braintree_$attributeName, or returns
  15. * an array with a single element containing the value of that array element
  16. *
  17. * @param array $attribArray attributes from a search response
  18. * @param string $attributeName indicates which element of the passed array to extract
  19. *
  20. * @return array array of Braintree_$attributeName objects, or a single element array
  21. */
  22. public static function extractAttributeAsArray(& $attribArray, $attributeName)
  23. {
  24. if(!isset($attribArray[$attributeName])):
  25. return array();
  26. endif;
  27. // get what should be an array from the passed array
  28. $data = $attribArray[$attributeName];
  29. // set up the class that will be used to convert each array element
  30. $classFactory = self::buildClassName($attributeName) . '::factory';
  31. if(is_array($data)):
  32. // create an object from the data in each element
  33. $objectArray = array_map($classFactory, $data);
  34. else:
  35. return array($data);
  36. endif;
  37. unset($attribArray[$attributeName]);
  38. return $objectArray;
  39. }
  40. /**
  41. * throws an exception based on the type of error
  42. * @param string $statusCode HTTP status code to throw exception from
  43. * @throws Braintree_Exception multiple types depending on the error
  44. *
  45. */
  46. public static function throwStatusCodeException($statusCode, $message=null)
  47. {
  48. switch($statusCode) {
  49. case 401:
  50. throw new Braintree_Exception_Authentication();
  51. break;
  52. case 403:
  53. throw new Braintree_Exception_Authorization($message);
  54. break;
  55. case 404:
  56. throw new Braintree_Exception_NotFound();
  57. break;
  58. case 426:
  59. throw new Braintree_Exception_UpgradeRequired();
  60. break;
  61. case 500:
  62. throw new Braintree_Exception_ServerError();
  63. break;
  64. case 503:
  65. throw new Braintree_Exception_DownForMaintenance();
  66. break;
  67. default:
  68. throw new Braintree_Exception_Unexpected('Unexpected HTTP_RESPONSE #'.$statusCode);
  69. break;
  70. }
  71. }
  72. /**
  73. * removes the Braintree_ header from a classname
  74. *
  75. * @param string $name Braintree_ClassName
  76. * @return camelCased classname minus Braintree_ header
  77. */
  78. public static function cleanClassName($name)
  79. {
  80. $classNamesToResponseKeys = array(
  81. 'CreditCard' => 'creditCard',
  82. 'Customer' => 'customer',
  83. 'Subscription' => 'subscription',
  84. 'Transaction' => 'transaction',
  85. 'CreditCardVerification' => 'verification',
  86. 'AddOn' => 'addOn',
  87. 'Discount' => 'discount',
  88. 'Plan' => 'plan',
  89. 'Address' => 'address',
  90. 'SettlementBatchSummary' => 'settlementBatchSummary',
  91. 'MerchantAccount' => 'merchantAccount',
  92. 'PayPalAccount' => 'paypalAccount'
  93. );
  94. $name = str_replace('Braintree_', '', $name);
  95. return $classNamesToResponseKeys[$name];
  96. }
  97. /**
  98. *
  99. * @param string $name className
  100. * @return string Braintree_ClassName
  101. */
  102. public static function buildClassName($name)
  103. {
  104. $responseKeysToClassNames = array(
  105. 'creditCard' => 'CreditCard',
  106. 'customer' => 'Customer',
  107. 'subscription' => 'Subscription',
  108. 'transaction' => 'Transaction',
  109. 'verification' => 'CreditCardVerification',
  110. 'addOn' => 'AddOn',
  111. 'discount' => 'Discount',
  112. 'plan' => 'Plan',
  113. 'address' => 'Address',
  114. 'settlementBatchSummary' => 'SettlementBatchSummary',
  115. 'merchantAccount' => 'MerchantAccount'
  116. );
  117. return 'Braintree_' . $responseKeysToClassNames[$name];
  118. }
  119. /**
  120. * convert alpha-beta-gamma to alphaBetaGamma
  121. *
  122. * @access public
  123. * @param string $string
  124. * @return string modified string
  125. */
  126. public static function delimiterToCamelCase($string, $delimiter = '[\-\_]')
  127. {
  128. // php doesn't garbage collect functions created by create_function()
  129. // so use a static variable to avoid adding a new function to memory
  130. // every time this function is called.
  131. static $callback = null;
  132. if ($callback === null) {
  133. $callback = create_function('$matches', 'return strtoupper($matches[1]);');
  134. }
  135. return preg_replace_callback('/' . $delimiter . '(\w)/', $callback, $string);
  136. }
  137. /**
  138. * convert alpha-beta-gamma to alpha_beta_gamma
  139. *
  140. * @access public
  141. * @param string $string
  142. * @return string modified string
  143. */
  144. public static function delimiterToUnderscore($string)
  145. {
  146. return preg_replace('/-/', '_', $string);
  147. }
  148. /**
  149. * find capitals and convert to delimiter + lowercase
  150. *
  151. * @access public
  152. * @param var $string
  153. * @return var modified string
  154. */
  155. public static function camelCaseToDelimiter($string, $delimiter = '-')
  156. {
  157. // php doesn't garbage collect functions created by create_function()
  158. // so use a static variable to avoid adding a new function to memory
  159. // every time this function is called.
  160. static $callbacks = array();
  161. if (!isset($callbacks[$delimiter])) {
  162. $callbacks[$delimiter] = create_function('$matches', "return '$delimiter' . strtolower(\$matches[1]);");
  163. }
  164. return preg_replace_callback('/([A-Z])/', $callbacks[$delimiter], $string);
  165. }
  166. /**
  167. *
  168. * @param array $array associative array to implode
  169. * @param string $separator (optional, defaults to =)
  170. * @param string $glue (optional, defaults to ', ')
  171. */
  172. public static function implodeAssociativeArray($array, $separator = '=', $glue = ', ')
  173. {
  174. // build a new array with joined keys and values
  175. $tmpArray = null;
  176. foreach ($array AS $key => $value) {
  177. $tmpArray[] = $key . $separator . $value;
  178. }
  179. // implode and return the new array
  180. return (is_array($tmpArray)) ? implode($glue, $tmpArray) : false;
  181. }
  182. public static function attributesToString($attributes) {
  183. $printableAttribs = array();
  184. foreach ($attributes AS $key => $value) {
  185. if (is_array($value)) {
  186. $pAttrib = Braintree_Util::attributesToString($value);
  187. } else if ($value instanceof DateTime) {
  188. $pAttrib = $value->format(DateTime::RFC850);
  189. } else {
  190. $pAttrib = $value;
  191. }
  192. $printableAttribs[$key] = sprintf('%s', $pAttrib);
  193. }
  194. return Braintree_Util::implodeAssociativeArray($printableAttribs);
  195. }
  196. /**
  197. * verify user request structure
  198. *
  199. * compares the expected signature of a gateway request
  200. * against the actual structure sent by the user
  201. *
  202. * @param array $signature
  203. * @param array $attributes
  204. */
  205. public static function verifyKeys($signature, $attributes)
  206. {
  207. $validKeys = self::_flattenArray($signature);
  208. $userKeys = self::_flattenUserKeys($attributes);
  209. $invalidKeys = array_diff($userKeys, $validKeys);
  210. $invalidKeys = self::_removeWildcardKeys($validKeys, $invalidKeys);
  211. if(!empty($invalidKeys)) {
  212. asort($invalidKeys);
  213. $sortedList = join(', ', $invalidKeys);
  214. throw new InvalidArgumentException('invalid keys: '. $sortedList);
  215. }
  216. }
  217. /**
  218. * flattens a numerically indexed nested array to a single level
  219. * @param array $keys
  220. * @param string $namespace
  221. * @return array
  222. */
  223. private static function _flattenArray($keys, $namespace = null)
  224. {
  225. $flattenedArray = array();
  226. foreach($keys AS $key) {
  227. if(is_array($key)) {
  228. $theKeys = array_keys($key);
  229. $theValues = array_values($key);
  230. $scope = $theKeys[0];
  231. $fullKey = empty($namespace) ? $scope : $namespace . '[' . $scope . ']';
  232. $flattenedArray = array_merge($flattenedArray, self::_flattenArray($theValues[0], $fullKey));
  233. } else {
  234. $fullKey = empty($namespace) ? $key : $namespace . '[' . $key . ']';
  235. $flattenedArray[] = $fullKey;
  236. }
  237. }
  238. sort($flattenedArray);
  239. return $flattenedArray;
  240. }
  241. private static function _flattenUserKeys($keys, $namespace = null)
  242. {
  243. $flattenedArray = array();
  244. foreach($keys AS $key => $value) {
  245. $fullKey = empty($namespace) ? $key : $namespace;
  246. if (!is_numeric($key) && $namespace != null) {
  247. $fullKey .= '[' . $key . ']';
  248. }
  249. if (is_numeric($key) && is_string($value)) {
  250. $fullKey .= '[' . $value . ']';
  251. }
  252. if(is_array($value)) {
  253. $more = self::_flattenUserKeys($value, $fullKey);
  254. $flattenedArray = array_merge($flattenedArray, $more);
  255. } else {
  256. $flattenedArray[] = $fullKey;
  257. }
  258. }
  259. sort($flattenedArray);
  260. return $flattenedArray;
  261. }
  262. /**
  263. * removes wildcard entries from the invalid keys array
  264. * @param array $validKeys
  265. * @param <array $invalidKeys
  266. * @return array
  267. */
  268. private static function _removeWildcardKeys($validKeys, $invalidKeys)
  269. {
  270. foreach($validKeys AS $key) {
  271. if (stristr($key, '[_anyKey_]')) {
  272. $wildcardKey = str_replace('[_anyKey_]', '', $key);
  273. foreach ($invalidKeys AS $index => $invalidKey) {
  274. if (stristr($invalidKey, $wildcardKey)) {
  275. unset($invalidKeys[$index]);
  276. }
  277. }
  278. }
  279. }
  280. return $invalidKeys;
  281. }
  282. }