AddressGateway.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. namespace Braintree;
  3. use InvalidArgumentException;
  4. /**
  5. * Braintree AddressGateway module
  6. * PHP Version 5
  7. * Creates and manages Braintree Addresses
  8. *
  9. * An Address belongs to a Customer. It can be associated to a
  10. * CreditCard as the billing address. It can also be used
  11. * as the shipping address when creating a Transaction.
  12. *
  13. * @package Braintree
  14. */
  15. class AddressGateway
  16. {
  17. /**
  18. *
  19. * @var Gateway
  20. */
  21. private $_gateway;
  22. /**
  23. *
  24. * @var Configuration
  25. */
  26. private $_config;
  27. /**
  28. *
  29. * @var Http
  30. */
  31. private $_http;
  32. /**
  33. *
  34. * @param Gateway $gateway
  35. */
  36. public function __construct($gateway)
  37. {
  38. $this->_gateway = $gateway;
  39. $this->_config = $gateway->config;
  40. $this->_config->assertHasAccessTokenOrKeys();
  41. $this->_http = new Http($gateway->config);
  42. }
  43. /* public class methods */
  44. /**
  45. *
  46. * @access public
  47. * @param array $attribs
  48. * @return Result\Successful|Result\Error
  49. */
  50. public function create($attribs)
  51. {
  52. Util::verifyKeys(self::createSignature(), $attribs);
  53. $customerId = isset($attribs['customerId']) ?
  54. $attribs['customerId'] :
  55. null;
  56. $this->_validateCustomerId($customerId);
  57. unset($attribs['customerId']);
  58. try {
  59. return $this->_doCreate(
  60. '/customers/' . $customerId . '/addresses',
  61. ['address' => $attribs]
  62. );
  63. } catch (Exception\NotFound $e) {
  64. throw new Exception\NotFound(
  65. 'Customer ' . $customerId . ' not found.'
  66. );
  67. }
  68. }
  69. /**
  70. * attempts the create operation assuming all data will validate
  71. * returns a Address object instead of a Result
  72. *
  73. * @access public
  74. * @param array $attribs
  75. * @return self
  76. * @throws Exception\ValidationError
  77. */
  78. public function createNoValidate($attribs)
  79. {
  80. $result = $this->create($attribs);
  81. return Util::returnObjectOrThrowException(__CLASS__, $result);
  82. }
  83. /**
  84. * delete an address by id
  85. *
  86. * @param mixed $customerOrId
  87. * @param string $addressId
  88. */
  89. public function delete($customerOrId = null, $addressId = null)
  90. {
  91. $this->_validateId($addressId);
  92. $customerId = $this->_determineCustomerId($customerOrId);
  93. $path = $this->_config->merchantPath() . '/customers/' . $customerId . '/addresses/' . $addressId;
  94. $this->_http->delete($path);
  95. return new Result\Successful();
  96. }
  97. /**
  98. * find an address by id
  99. *
  100. * Finds the address with the given <b>addressId</b> that is associated
  101. * to the given <b>customerOrId</b>.
  102. * If the address cannot be found, a NotFound exception will be thrown.
  103. *
  104. *
  105. * @access public
  106. * @param mixed $customerOrId
  107. * @param string $addressId
  108. * @return Address
  109. * @throws Exception\NotFound
  110. */
  111. public function find($customerOrId, $addressId)
  112. {
  113. $customerId = $this->_determineCustomerId($customerOrId);
  114. $this->_validateId($addressId);
  115. try {
  116. $path = $this->_config->merchantPath() . '/customers/' . $customerId . '/addresses/' . $addressId;
  117. $response = $this->_http->get($path);
  118. return Address::factory($response['address']);
  119. } catch (Exception\NotFound $e) {
  120. throw new Exception\NotFound(
  121. 'address for customer ' . $customerId .
  122. ' with id ' . $addressId . ' not found.'
  123. );
  124. }
  125. }
  126. /**
  127. * updates the address record
  128. *
  129. * if calling this method in context,
  130. * customerOrId is the 2nd attribute, addressId 3rd.
  131. * customerOrId & addressId are not sent in object context.
  132. *
  133. *
  134. * @access public
  135. * @param array $attributes
  136. * @param mixed $customerOrId (only used in call)
  137. * @param string $addressId (only used in call)
  138. * @return Result\Successful|Result\Error
  139. */
  140. public function update($customerOrId, $addressId, $attributes)
  141. {
  142. $this->_validateId($addressId);
  143. $customerId = $this->_determineCustomerId($customerOrId);
  144. Util::verifyKeys(self::updateSignature(), $attributes);
  145. $path = $this->_config->merchantPath() . '/customers/' . $customerId . '/addresses/' . $addressId;
  146. $response = $this->_http->put($path, ['address' => $attributes]);
  147. return $this->_verifyGatewayResponse($response);
  148. }
  149. /**
  150. * update an address record, assuming validations will pass
  151. *
  152. * if calling this method in context,
  153. * customerOrId is the 2nd attribute, addressId 3rd.
  154. * customerOrId & addressId are not sent in object context.
  155. *
  156. * @access public
  157. * @param array $transactionAttribs
  158. * @param string $customerId
  159. * @return Transaction
  160. * @throws Exception\ValidationsFailed
  161. * @see Address::update()
  162. */
  163. public function updateNoValidate($customerOrId, $addressId, $attributes)
  164. {
  165. $result = $this->update($customerOrId, $addressId, $attributes);
  166. return Util::returnObjectOrThrowException(__CLASS__, $result);
  167. }
  168. /**
  169. * creates a full array signature of a valid create request
  170. * @return array gateway create request format
  171. */
  172. public static function createSignature()
  173. {
  174. return [
  175. 'company', 'countryCodeAlpha2', 'countryCodeAlpha3', 'countryCodeNumeric',
  176. 'countryName', 'customerId', 'extendedAddress', 'firstName',
  177. 'lastName', 'locality', 'postalCode', 'region', 'streetAddress'
  178. ];
  179. }
  180. /**
  181. * creates a full array signature of a valid update request
  182. * @return array gateway update request format
  183. */
  184. public static function updateSignature()
  185. {
  186. // TODO: remove customerId from update signature
  187. return self::createSignature();
  188. }
  189. /**
  190. * verifies that a valid address id is being used
  191. * @ignore
  192. * @param string $id address id
  193. * @throws InvalidArgumentException
  194. */
  195. private function _validateId($id = null)
  196. {
  197. if (empty($id) || trim($id) == "") {
  198. throw new InvalidArgumentException(
  199. 'expected address id to be set'
  200. );
  201. }
  202. if (!preg_match('/^[0-9A-Za-z_-]+$/', $id)) {
  203. throw new InvalidArgumentException(
  204. $id . ' is an invalid address id.'
  205. );
  206. }
  207. }
  208. /**
  209. * verifies that a valid customer id is being used
  210. * @ignore
  211. * @param string $id customer id
  212. * @throws InvalidArgumentException
  213. */
  214. private function _validateCustomerId($id = null)
  215. {
  216. if (empty($id) || trim($id) == "") {
  217. throw new InvalidArgumentException(
  218. 'expected customer id to be set'
  219. );
  220. }
  221. if (!preg_match('/^[0-9A-Za-z_-]+$/', $id)) {
  222. throw new InvalidArgumentException(
  223. $id . ' is an invalid customer id.'
  224. );
  225. }
  226. }
  227. /**
  228. * determines if a string id or Customer object was passed
  229. * @ignore
  230. * @param mixed $customerOrId
  231. * @return string customerId
  232. */
  233. private function _determineCustomerId($customerOrId)
  234. {
  235. $customerId = ($customerOrId instanceof Customer) ? $customerOrId->id : $customerOrId;
  236. $this->_validateCustomerId($customerId);
  237. return $customerId;
  238. }
  239. /* private class methods */
  240. /**
  241. * sends the create request to the gateway
  242. * @ignore
  243. * @param string $subPath
  244. * @param array $params
  245. * @return Result\Successful|Result\Error
  246. */
  247. private function _doCreate($subPath, $params)
  248. {
  249. $fullPath = $this->_config->merchantPath() . $subPath;
  250. $response = $this->_http->post($fullPath, $params);
  251. return $this->_verifyGatewayResponse($response);
  252. }
  253. /**
  254. * generic method for validating incoming gateway responses
  255. *
  256. * creates a new Address object and encapsulates
  257. * it inside a Result\Successful object, or
  258. * encapsulates an Errors object inside a Result\Error
  259. * alternatively, throws an Unexpected exception if the response is invalid
  260. *
  261. * @ignore
  262. * @param array $response gateway response values
  263. * @return Result\Successful|Result\Error
  264. * @throws Exception\Unexpected
  265. */
  266. private function _verifyGatewayResponse($response)
  267. {
  268. if (isset($response['address'])) {
  269. // return a populated instance of Address
  270. return new Result\Successful(
  271. Address::factory($response['address'])
  272. );
  273. } else if (isset($response['apiErrorResponse'])) {
  274. return new Result\Error($response['apiErrorResponse']);
  275. } else {
  276. throw new Exception\Unexpected(
  277. "Expected address or apiErrorResponse"
  278. );
  279. }
  280. }
  281. }
  282. class_alias('Braintree\AddressGateway', 'Braintree_AddressGateway');