Utils.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. if ( !class_exists('Puc_v4p11_Utils', false) ):
  3. class Puc_v4p11_Utils {
  4. /**
  5. * Get a value from a nested array or object based on a path.
  6. *
  7. * @param array|object|null $collection Get an entry from this array.
  8. * @param array|string $path A list of array keys in hierarchy order, or a string path like "foo.bar.baz".
  9. * @param mixed $default The value to return if the specified path is not found.
  10. * @param string $separator Path element separator. Only applies to string paths.
  11. * @return mixed
  12. */
  13. public static function get($collection, $path, $default = null, $separator = '.') {
  14. if ( is_string($path) ) {
  15. $path = explode($separator, $path);
  16. }
  17. //Follow the $path into $input as far as possible.
  18. $currentValue = $collection;
  19. foreach ($path as $node) {
  20. if ( is_array($currentValue) && isset($currentValue[$node]) ) {
  21. $currentValue = $currentValue[$node];
  22. } else if ( is_object($currentValue) && isset($currentValue->$node) ) {
  23. $currentValue = $currentValue->$node;
  24. } else {
  25. return $default;
  26. }
  27. }
  28. return $currentValue;
  29. }
  30. /**
  31. * Get the first array element that is not empty.
  32. *
  33. * @param array $values
  34. * @param mixed|null $default Returns this value if there are no non-empty elements.
  35. * @return mixed|null
  36. */
  37. public static function findNotEmpty($values, $default = null) {
  38. if ( empty($values) ) {
  39. return $default;
  40. }
  41. foreach ($values as $value) {
  42. if ( !empty($value) ) {
  43. return $value;
  44. }
  45. }
  46. return $default;
  47. }
  48. /**
  49. * Check if the input string starts with the specified prefix.
  50. *
  51. * @param string $input
  52. * @param string $prefix
  53. * @return bool
  54. */
  55. public static function startsWith($input, $prefix) {
  56. $length = strlen($prefix);
  57. return (substr($input, 0, $length) === $prefix);
  58. }
  59. }
  60. endif;