StripeObject.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. <?php
  2. namespace Stripe;
  3. /**
  4. * Class StripeObject.
  5. */
  6. class StripeObject implements \ArrayAccess, \Countable, \JsonSerializable
  7. {
  8. /** @var Util\RequestOptions */
  9. protected $_opts;
  10. /** @var array */
  11. protected $_originalValues;
  12. /** @var array */
  13. protected $_values;
  14. /** @var Util\Set */
  15. protected $_unsavedValues;
  16. /** @var Util\Set */
  17. protected $_transientValues;
  18. /** @var null|array */
  19. protected $_retrieveOptions;
  20. /** @var null|ApiResponse */
  21. protected $_lastResponse;
  22. /**
  23. * @return Util\Set Attributes that should not be sent to the API because
  24. * they're not updatable (e.g. ID).
  25. */
  26. public static function getPermanentAttributes()
  27. {
  28. static $permanentAttributes = null;
  29. if (null === $permanentAttributes) {
  30. $permanentAttributes = new Util\Set([
  31. 'id',
  32. ]);
  33. }
  34. return $permanentAttributes;
  35. }
  36. /**
  37. * Additive objects are subobjects in the API that don't have the same
  38. * semantics as most subobjects, which are fully replaced when they're set.
  39. *
  40. * This is best illustrated by example. The `source` parameter sent when
  41. * updating a subscription is *not* additive; if we set it:
  42. *
  43. * source[object]=card&source[number]=123
  44. *
  45. * We expect the old `source` object to have been overwritten completely. If
  46. * the previous source had an `address_state` key associated with it and we
  47. * didn't send one this time, that value of `address_state` is gone.
  48. *
  49. * By contrast, additive objects are those that will have new data added to
  50. * them while keeping any existing data in place. The only known case of its
  51. * use is for `metadata`, but it could in theory be more general. As an
  52. * example, say we have a `metadata` object that looks like this on the
  53. * server side:
  54. *
  55. * metadata = ["old" => "old_value"]
  56. *
  57. * If we update the object with `metadata[new]=new_value`, the server side
  58. * object now has *both* fields:
  59. *
  60. * metadata = ["old" => "old_value", "new" => "new_value"]
  61. *
  62. * This is okay in itself because usually users will want to treat it as
  63. * additive:
  64. *
  65. * $obj->metadata["new"] = "new_value";
  66. * $obj->save();
  67. *
  68. * However, in other cases, they may want to replace the entire existing
  69. * contents:
  70. *
  71. * $obj->metadata = ["new" => "new_value"];
  72. * $obj->save();
  73. *
  74. * This is where things get a little bit tricky because in order to clear
  75. * any old keys that may have existed, we actually have to send an explicit
  76. * empty string to the server. So the operation above would have to send
  77. * this form to get the intended behavior:
  78. *
  79. * metadata[old]=&metadata[new]=new_value
  80. *
  81. * This method allows us to track which parameters are considered additive,
  82. * and lets us behave correctly where appropriate when serializing
  83. * parameters to be sent.
  84. *
  85. * @return Util\Set Set of additive parameters
  86. */
  87. public static function getAdditiveParams()
  88. {
  89. static $additiveParams = null;
  90. if (null === $additiveParams) {
  91. // Set `metadata` as additive so that when it's set directly we remember
  92. // to clear keys that may have been previously set by sending empty
  93. // values for them.
  94. //
  95. // It's possible that not every object has `metadata`, but having this
  96. // option set when there is no `metadata` field is not harmful.
  97. $additiveParams = new Util\Set([
  98. 'metadata',
  99. ]);
  100. }
  101. return $additiveParams;
  102. }
  103. public function __construct($id = null, $opts = null)
  104. {
  105. list($id, $this->_retrieveOptions) = Util\Util::normalizeId($id);
  106. $this->_opts = Util\RequestOptions::parse($opts);
  107. $this->_originalValues = [];
  108. $this->_values = [];
  109. $this->_unsavedValues = new Util\Set();
  110. $this->_transientValues = new Util\Set();
  111. if (null !== $id) {
  112. $this->_values['id'] = $id;
  113. }
  114. }
  115. // Standard accessor magic methods
  116. public function __set($k, $v)
  117. {
  118. if (static::getPermanentAttributes()->includes($k)) {
  119. throw new Exception\InvalidArgumentException(
  120. "Cannot set {$k} on this object. HINT: you can't set: " .
  121. \implode(', ', static::getPermanentAttributes()->toArray())
  122. );
  123. }
  124. if ('' === $v) {
  125. throw new Exception\InvalidArgumentException(
  126. 'You cannot set \'' . $k . '\'to an empty string. '
  127. . 'We interpret empty strings as NULL in requests. '
  128. . 'You may set obj->' . $k . ' = NULL to delete the property'
  129. );
  130. }
  131. $this->_values[$k] = Util\Util::convertToStripeObject($v, $this->_opts);
  132. $this->dirtyValue($this->_values[$k]);
  133. $this->_unsavedValues->add($k);
  134. }
  135. public function __isset($k)
  136. {
  137. return isset($this->_values[$k]);
  138. }
  139. public function __unset($k)
  140. {
  141. unset($this->_values[$k]);
  142. $this->_transientValues->add($k);
  143. $this->_unsavedValues->discard($k);
  144. }
  145. public function &__get($k)
  146. {
  147. // function should return a reference, using $nullval to return a reference to null
  148. $nullval = null;
  149. if (!empty($this->_values) && \array_key_exists($k, $this->_values)) {
  150. return $this->_values[$k];
  151. }
  152. if (!empty($this->_transientValues) && $this->_transientValues->includes($k)) {
  153. $class = static::class;
  154. $attrs = \implode(', ', \array_keys($this->_values));
  155. $message = "Stripe Notice: Undefined property of {$class} instance: {$k}. "
  156. . "HINT: The {$k} attribute was set in the past, however. "
  157. . 'It was then wiped when refreshing the object '
  158. . "with the result returned by Stripe's API, "
  159. . 'probably as a result of a save(). The attributes currently '
  160. . "available on this object are: {$attrs}";
  161. Stripe::getLogger()->error($message);
  162. return $nullval;
  163. }
  164. $class = static::class;
  165. Stripe::getLogger()->error("Stripe Notice: Undefined property of {$class} instance: {$k}");
  166. return $nullval;
  167. }
  168. // Magic method for var_dump output. Only works with PHP >= 5.6
  169. public function __debugInfo()
  170. {
  171. return $this->_values;
  172. }
  173. // ArrayAccess methods
  174. public function offsetSet($k, $v)
  175. {
  176. $this->{$k} = $v;
  177. }
  178. public function offsetExists($k)
  179. {
  180. return \array_key_exists($k, $this->_values);
  181. }
  182. public function offsetUnset($k)
  183. {
  184. unset($this->{$k});
  185. }
  186. public function offsetGet($k)
  187. {
  188. return \array_key_exists($k, $this->_values) ? $this->_values[$k] : null;
  189. }
  190. // Countable method
  191. public function count()
  192. {
  193. return \count($this->_values);
  194. }
  195. public function keys()
  196. {
  197. return \array_keys($this->_values);
  198. }
  199. public function values()
  200. {
  201. return \array_values($this->_values);
  202. }
  203. /**
  204. * This unfortunately needs to be public to be used in Util\Util.
  205. *
  206. * @param array $values
  207. * @param null|array|string|Util\RequestOptions $opts
  208. *
  209. * @return static the object constructed from the given values
  210. */
  211. public static function constructFrom($values, $opts = null)
  212. {
  213. $obj = new static(isset($values['id']) ? $values['id'] : null);
  214. $obj->refreshFrom($values, $opts);
  215. return $obj;
  216. }
  217. /**
  218. * Refreshes this object using the provided values.
  219. *
  220. * @param array $values
  221. * @param null|array|string|Util\RequestOptions $opts
  222. * @param bool $partial defaults to false
  223. */
  224. public function refreshFrom($values, $opts, $partial = false)
  225. {
  226. $this->_opts = Util\RequestOptions::parse($opts);
  227. $this->_originalValues = self::deepCopy($values);
  228. if ($values instanceof StripeObject) {
  229. $values = $values->toArray();
  230. }
  231. // Wipe old state before setting new. This is useful for e.g. updating a
  232. // customer, where there is no persistent card parameter. Mark those values
  233. // which don't persist as transient
  234. if ($partial) {
  235. $removed = new Util\Set();
  236. } else {
  237. $removed = new Util\Set(\array_diff(\array_keys($this->_values), \array_keys($values)));
  238. }
  239. foreach ($removed->toArray() as $k) {
  240. unset($this->{$k});
  241. }
  242. $this->updateAttributes($values, $opts, false);
  243. foreach ($values as $k => $v) {
  244. $this->_transientValues->discard($k);
  245. $this->_unsavedValues->discard($k);
  246. }
  247. }
  248. /**
  249. * Mass assigns attributes on the model.
  250. *
  251. * @param array $values
  252. * @param null|array|string|Util\RequestOptions $opts
  253. * @param bool $dirty defaults to true
  254. */
  255. public function updateAttributes($values, $opts = null, $dirty = true)
  256. {
  257. foreach ($values as $k => $v) {
  258. // Special-case metadata to always be cast as a StripeObject
  259. // This is necessary in case metadata is empty, as PHP arrays do
  260. // not differentiate between lists and hashes, and we consider
  261. // empty arrays to be lists.
  262. if (('metadata' === $k) && (\is_array($v))) {
  263. $this->_values[$k] = StripeObject::constructFrom($v, $opts);
  264. } else {
  265. $this->_values[$k] = Util\Util::convertToStripeObject($v, $opts);
  266. }
  267. if ($dirty) {
  268. $this->dirtyValue($this->_values[$k]);
  269. }
  270. $this->_unsavedValues->add($k);
  271. }
  272. }
  273. /**
  274. * @param bool $force defaults to false
  275. *
  276. * @return array a recursive mapping of attributes to values for this object,
  277. * including the proper value for deleted attributes
  278. */
  279. public function serializeParameters($force = false)
  280. {
  281. $updateParams = [];
  282. foreach ($this->_values as $k => $v) {
  283. // There are a few reasons that we may want to add in a parameter for
  284. // update:
  285. //
  286. // 1. The `$force` option has been set.
  287. // 2. We know that it was modified.
  288. // 3. Its value is a StripeObject. A StripeObject may contain modified
  289. // values within in that its parent StripeObject doesn't know about.
  290. //
  291. $original = \array_key_exists($k, $this->_originalValues) ? $this->_originalValues[$k] : null;
  292. $unsaved = $this->_unsavedValues->includes($k);
  293. if ($force || $unsaved || $v instanceof StripeObject) {
  294. $updateParams[$k] = $this->serializeParamsValue(
  295. $this->_values[$k],
  296. $original,
  297. $unsaved,
  298. $force,
  299. $k
  300. );
  301. }
  302. }
  303. // a `null` that makes it out of `serializeParamsValue` signals an empty
  304. // value that we shouldn't appear in the serialized form of the object
  305. return \array_filter(
  306. $updateParams,
  307. function ($v) {
  308. return null !== $v;
  309. }
  310. );
  311. }
  312. public function serializeParamsValue($value, $original, $unsaved, $force, $key = null)
  313. {
  314. // The logic here is that essentially any object embedded in another
  315. // object that had a `type` is actually an API resource of a different
  316. // type that's been included in the response. These other resources must
  317. // be updated from their proper endpoints, and therefore they are not
  318. // included when serializing even if they've been modified.
  319. //
  320. // There are _some_ known exceptions though.
  321. //
  322. // For example, if the value is unsaved (meaning the user has set it), and
  323. // it looks like the API resource is persisted with an ID, then we include
  324. // the object so that parameters are serialized with a reference to its
  325. // ID.
  326. //
  327. // Another example is that on save API calls it's sometimes desirable to
  328. // update a customer's default source by setting a new card (or other)
  329. // object with `->source=` and then saving the customer. The
  330. // `saveWithParent` flag to override the default behavior allows us to
  331. // handle these exceptions.
  332. //
  333. // We throw an error if a property was set explicitly but we can't do
  334. // anything with it because the integration is probably not working as the
  335. // user intended it to.
  336. if (null === $value) {
  337. return '';
  338. }
  339. if (($value instanceof ApiResource) && (!$value->saveWithParent)) {
  340. if (!$unsaved) {
  341. return null;
  342. }
  343. if (isset($value->id)) {
  344. return $value;
  345. }
  346. throw new Exception\InvalidArgumentException(
  347. "Cannot save property `{$key}` containing an API resource of type " .
  348. \get_class($value) . ". It doesn't appear to be persisted and is " .
  349. 'not marked as `saveWithParent`.'
  350. );
  351. }
  352. if (\is_array($value)) {
  353. if (Util\Util::isList($value)) {
  354. // Sequential array, i.e. a list
  355. $update = [];
  356. foreach ($value as $v) {
  357. $update[] = $this->serializeParamsValue($v, null, true, $force);
  358. }
  359. // This prevents an array that's unchanged from being resent.
  360. if ($update !== $this->serializeParamsValue($original, null, true, $force, $key)) {
  361. return $update;
  362. }
  363. } else {
  364. // Associative array, i.e. a map
  365. return Util\Util::convertToStripeObject($value, $this->_opts)->serializeParameters();
  366. }
  367. } elseif ($value instanceof StripeObject) {
  368. $update = $value->serializeParameters($force);
  369. if ($original && $unsaved && $key && static::getAdditiveParams()->includes($key)) {
  370. $update = \array_merge(self::emptyValues($original), $update);
  371. }
  372. return $update;
  373. } else {
  374. return $value;
  375. }
  376. }
  377. public function jsonSerialize()
  378. {
  379. return $this->toArray();
  380. }
  381. /**
  382. * Returns an associative array with the key and values composing the
  383. * Stripe object.
  384. *
  385. * @return array the associative array
  386. */
  387. public function toArray()
  388. {
  389. $maybeToArray = function ($value) {
  390. if (null === $value) {
  391. return null;
  392. }
  393. return \is_object($value) && \method_exists($value, 'toArray') ? $value->toArray() : $value;
  394. };
  395. return \array_reduce(\array_keys($this->_values), function ($acc, $k) use ($maybeToArray) {
  396. if ('_' === \substr((string) $k, 0, 1)) {
  397. return $acc;
  398. }
  399. $v = $this->_values[$k];
  400. if (Util\Util::isList($v)) {
  401. $acc[$k] = \array_map($maybeToArray, $v);
  402. } else {
  403. $acc[$k] = $maybeToArray($v);
  404. }
  405. return $acc;
  406. }, []);
  407. }
  408. /**
  409. * Returns a pretty JSON representation of the Stripe object.
  410. *
  411. * @return string the JSON representation of the Stripe object
  412. */
  413. public function toJSON()
  414. {
  415. return \json_encode($this->toArray(), \JSON_PRETTY_PRINT);
  416. }
  417. public function __toString()
  418. {
  419. $class = static::class;
  420. return $class . ' JSON: ' . $this->toJSON();
  421. }
  422. /**
  423. * Sets all keys within the StripeObject as unsaved so that they will be
  424. * included with an update when `serializeParameters` is called. This
  425. * method is also recursive, so any StripeObjects contained as values or
  426. * which are values in a tenant array are also marked as dirty.
  427. */
  428. public function dirty()
  429. {
  430. $this->_unsavedValues = new Util\Set(\array_keys($this->_values));
  431. foreach ($this->_values as $k => $v) {
  432. $this->dirtyValue($v);
  433. }
  434. }
  435. protected function dirtyValue($value)
  436. {
  437. if (\is_array($value)) {
  438. foreach ($value as $v) {
  439. $this->dirtyValue($v);
  440. }
  441. } elseif ($value instanceof StripeObject) {
  442. $value->dirty();
  443. }
  444. }
  445. /**
  446. * Produces a deep copy of the given object including support for arrays
  447. * and StripeObjects.
  448. *
  449. * @param mixed $obj
  450. */
  451. protected static function deepCopy($obj)
  452. {
  453. if (\is_array($obj)) {
  454. $copy = [];
  455. foreach ($obj as $k => $v) {
  456. $copy[$k] = self::deepCopy($v);
  457. }
  458. return $copy;
  459. }
  460. if ($obj instanceof StripeObject) {
  461. return $obj::constructFrom(
  462. self::deepCopy($obj->_values),
  463. clone $obj->_opts
  464. );
  465. }
  466. return $obj;
  467. }
  468. /**
  469. * Returns a hash of empty values for all the values that are in the given
  470. * StripeObject.
  471. *
  472. * @param mixed $obj
  473. */
  474. public static function emptyValues($obj)
  475. {
  476. if (\is_array($obj)) {
  477. $values = $obj;
  478. } elseif ($obj instanceof StripeObject) {
  479. $values = $obj->_values;
  480. } else {
  481. throw new Exception\InvalidArgumentException(
  482. 'empty_values got unexpected object type: ' . \get_class($obj)
  483. );
  484. }
  485. return \array_fill_keys(\array_keys($values), '');
  486. }
  487. /**
  488. * @return null|ApiResponse The last response from the Stripe API
  489. */
  490. public function getLastResponse()
  491. {
  492. return $this->_lastResponse;
  493. }
  494. /**
  495. * Sets the last response from the Stripe API.
  496. *
  497. * @param ApiResponse $resp
  498. */
  499. public function setLastResponse($resp)
  500. {
  501. $this->_lastResponse = $resp;
  502. }
  503. /**
  504. * Indicates whether or not the resource has been deleted on the server.
  505. * Note that some, but not all, resources can indicate whether they have
  506. * been deleted.
  507. *
  508. * @return bool whether the resource is deleted
  509. */
  510. public function isDeleted()
  511. {
  512. return isset($this->_values['deleted']) ? $this->_values['deleted'] : false;
  513. }
  514. }