Utils.php 1.9 KB

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