An updated theme (based on Atticus Finch) for ClassicPress
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.0 KiB

3 years ago
  1. <?php
  2. if ( !class_exists('Puc_v4p1_Utils', false) ):
  3. class Puc_v4p1_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. if ( empty($path) ) {
  18. return $default;
  19. }
  20. //Follow the $path into $input as far as possible.
  21. $currentValue = $collection;
  22. $pathExists = true;
  23. foreach ($path as $node) {
  24. if ( is_array($currentValue) && isset($currentValue[$node]) ) {
  25. $currentValue = $currentValue[$node];
  26. } else if ( is_object($currentValue) && isset($currentValue->$node) ) {
  27. $currentValue = $currentValue->$node;
  28. } else {
  29. $pathExists = false;
  30. break;
  31. }
  32. }
  33. if ( $pathExists ) {
  34. return $currentValue;
  35. }
  36. return $default;
  37. }
  38. /**
  39. * Get the first array element that is not empty.
  40. *
  41. * @param array $values
  42. * @param mixed|null $default Returns this value if there are no non-empty elements.
  43. * @return mixed|null
  44. */
  45. public static function findNotEmpty($values, $default = null) {
  46. if ( empty($values) ) {
  47. return $default;
  48. }
  49. foreach ($values as $value) {
  50. if ( !empty($value) ) {
  51. return $value;
  52. }
  53. }
  54. return $default;
  55. }
  56. /**
  57. * Check if the input string starts with the specified prefix.
  58. *
  59. * @param string $input
  60. * @param string $prefix
  61. * @return bool
  62. */
  63. public static function startsWith($input, $prefix) {
  64. $length = strlen($prefix);
  65. return (substr($input, 0, $length) === $prefix);
  66. }
  67. }
  68. endif;