AbstractSimpleObject.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Api;
  7. /**
  8. * Base Class for simple data Objects
  9. * @SuppressWarnings(PHPMD.NumberOfChildren)
  10. */
  11. abstract class AbstractSimpleObject
  12. {
  13. /**
  14. * @var array
  15. */
  16. protected $_data;
  17. /**
  18. * Initialize internal storage
  19. *
  20. * @param array $data
  21. */
  22. public function __construct(array $data = [])
  23. {
  24. $this->_data = $data;
  25. }
  26. /**
  27. * Retrieves a value from the data array if set, or null otherwise.
  28. *
  29. * @param string $key
  30. * @return mixed|null
  31. */
  32. protected function _get($key)
  33. {
  34. return $this->_data[$key] ?? null;
  35. }
  36. /**
  37. * Set value for the given key
  38. *
  39. * @param string $key
  40. * @param mixed $value
  41. * @return $this
  42. */
  43. public function setData($key, $value)
  44. {
  45. $this->_data[$key] = $value;
  46. return $this;
  47. }
  48. /**
  49. * Return Data Object data in array format.
  50. *
  51. * @return array
  52. */
  53. public function __toArray()
  54. {
  55. $data = $this->_data;
  56. $hasToArray = function ($model) {
  57. return is_object($model) && method_exists($model, '__toArray') && is_callable([$model, '__toArray']);
  58. };
  59. foreach ($data as $key => $value) {
  60. if ($hasToArray($value)) {
  61. $data[$key] = $value->__toArray();
  62. } elseif (is_array($value)) {
  63. foreach ($value as $nestedKey => $nestedValue) {
  64. if ($hasToArray($nestedValue)) {
  65. $value[$nestedKey] = $nestedValue->__toArray();
  66. }
  67. }
  68. $data[$key] = $value;
  69. }
  70. }
  71. return $data;
  72. }
  73. }