ArrayObjectSearch.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. * Class to provide possibility to search for any object's property value by the name and value of another property
  9. */
  10. class ArrayObjectSearch
  11. {
  12. /**
  13. * Search for the value's value by specified key's name-value pair in the object
  14. * <pre>
  15. * Example of usage:
  16. * $data = array(
  17. * ValidationRuleBuilderObject('name' => 'min_text_length', 'value' => 0)
  18. * ValidationRuleBuilderObject('name' => 'max_text_length', 'value' => 255)
  19. * ValidationRuleBuilderObject('anyOtherName' => 'customName', 'anyOtherValue' => 'customValue')
  20. * );
  21. *
  22. * Call:
  23. * $maxDateValue = ArrayObjectSearch::getArrayElementByName(
  24. * $data,
  25. * 'max_text_length'
  26. * );
  27. * By default function looks for `value`'s value by the `name`'s value
  28. * Result: 255
  29. *
  30. * Call:
  31. * $customValue = ArrayObjectSearch::getArrayElementByName(
  32. * $data,
  33. * 'customName', //what key value to look for
  34. * 'anyOtherName', //where to look for
  35. * 'anyOtherValue' //where to return from
  36. * );
  37. * Result: 'customValue'
  38. * </pre>
  39. * @param object $data Object to search in
  40. * @param string $keyValue Value of the key property to search for
  41. * @param string $keyName Name of the key property to search for
  42. * @param string $valueName Name of the value property name
  43. * @return null|mixed
  44. */
  45. public static function getArrayElementByName($data, $keyValue, $keyName = 'name', $valueName = 'value')
  46. {
  47. $getter = 'get' . ucfirst($keyName);
  48. if (is_array($data)) {
  49. foreach ($data as $dataObject) {
  50. if (is_object($dataObject) && $dataObject->$getter() == $keyValue) {
  51. $valueGetter = 'get' . ucfirst($valueName);
  52. return $dataObject->$valueGetter();
  53. }
  54. }
  55. }
  56. return null;
  57. }
  58. }