AbstractDataObject.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Data;
  7. /**
  8. * Base Class for simple data Objects
  9. * @SuppressWarnings(PHPMD.NumberOfChildren)
  10. */
  11. abstract class AbstractDataObject
  12. {
  13. /**
  14. * @var array
  15. */
  16. protected $data;
  17. /**
  18. * Return Data Object data in array format.
  19. *
  20. * @return array
  21. */
  22. public function toArray()
  23. {
  24. $data = $this->data;
  25. $hasToArray = function ($model) {
  26. return is_object($model) && method_exists($model, 'toArray') && is_callable([$model, 'toArray']);
  27. };
  28. foreach ($data as $key => $value) {
  29. if ($hasToArray($value)) {
  30. $data[$key] = $value->toArray();
  31. } elseif (is_array($value)) {
  32. foreach ($value as $nestedKey => $nestedValue) {
  33. if ($hasToArray($nestedValue)) {
  34. $value[$nestedKey] = $nestedValue->toArray();
  35. }
  36. }
  37. $data[$key] = $value;
  38. }
  39. }
  40. return $data;
  41. }
  42. /**
  43. * Retrieves a value from the data array if set, or null otherwise.
  44. *
  45. * @param string $key
  46. * @return mixed|null
  47. */
  48. protected function get($key)
  49. {
  50. return $this->data[$key] ?? null;
  51. }
  52. }