ExtractTrait.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since CakePHP(tm) v 3.0.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\Collection;
  16. /**
  17. * Provides utility protected methods for extracting a property or column
  18. * from an array or object.
  19. */
  20. trait ExtractTrait {
  21. /**
  22. * Returns a callable that can be used to extract a property or column from
  23. * an array or object based on a dot separated path.
  24. *
  25. * @param string|callable $callback A dot separated path of column to follow
  26. * so that the final one can be returned or a callable that will take care
  27. * of doing that.
  28. * @return callable
  29. */
  30. protected function _propertyExtractor($callback) {
  31. if (is_string($callback)) {
  32. $path = $path = explode('.', $callback);
  33. $callback = function($element) use ($path) {
  34. return $this->_extract($element, $path);
  35. };
  36. }
  37. return $callback;
  38. }
  39. /**
  40. * Returns a column from $data that can be extracted
  41. * by iterating over the column names contained in $path
  42. *
  43. * @param array|\ArrayAccess $data
  44. * @param array $path
  45. * @return mixed
  46. */
  47. protected function _extract($data, $path) {
  48. $value = null;
  49. foreach ($path as $column) {
  50. if (!isset($data[$column])) {
  51. return null;
  52. }
  53. $value = $data[$column];
  54. $data = $value;
  55. }
  56. return $value;
  57. }
  58. }