|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace BNETDocs\Libraries\Core; |
| 4 | + |
| 5 | +class ArrayTypeCheck |
| 6 | +{ |
| 7 | + /** |
| 8 | + * Checks a particular array item to ensure it is of a particular type. |
| 9 | + * |
| 10 | + * @param mixed $instance The array item to check. |
| 11 | + * @param string $type The expected type for the array item. |
| 12 | + * @return bool Whether the item is of the particular type, or false if not. |
| 13 | + */ |
| 14 | + protected static function check(mixed $instance, string $type): bool |
| 15 | + { |
| 16 | + return (gettype($instance) == $type |
| 17 | + || (is_object($instance) && get_class($instance) == $type) |
| 18 | + || (is_resource($instance) && get_resource_type($instance) == $type)); |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Checks the keys of an array to ensure all items are of a particular type. |
| 23 | + * |
| 24 | + * @param array $instances The array to iterate and check. |
| 25 | + * @param string $type The expected type for each item in the array. |
| 26 | + * @return bool Whether all items are of the particular type, or false if not. |
| 27 | + */ |
| 28 | + public static function keys(array $instances, string $type): bool |
| 29 | + { |
| 30 | + foreach ($instances as $key => $instance) |
| 31 | + { |
| 32 | + if (!self::check($key, $type)) |
| 33 | + { |
| 34 | + return false; |
| 35 | + } |
| 36 | + } |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Checks keys and values of an array to ensure all items are of a particular type. |
| 42 | + * |
| 43 | + * @param array $instances The array to iterate and check. |
| 44 | + * @param string $type The expected type for each item in the array. |
| 45 | + * @return bool Whether all items are of the particular type, or false if not. |
| 46 | + */ |
| 47 | + public static function keysAndValues(array $instances, string $type): bool |
| 48 | + { |
| 49 | + foreach ($instances as $key => $instance) |
| 50 | + { |
| 51 | + if (!self::check($key, $type) && !self::check($instance, $type)) |
| 52 | + { |
| 53 | + return false; |
| 54 | + } |
| 55 | + } |
| 56 | + return true; |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Checks the values of an array to ensure all items are of a particular type. |
| 61 | + * |
| 62 | + * @param array $instances The array to iterate and check. |
| 63 | + * @param string $type The expected type for each item in the array. |
| 64 | + * @return bool Whether all items are of the particular type, or false if not. |
| 65 | + */ |
| 66 | + public static function values(array $instances, string $type): bool |
| 67 | + { |
| 68 | + foreach ($instances as $instance) |
| 69 | + { |
| 70 | + if (!self::check($instance, $type)) |
| 71 | + { |
| 72 | + return false; |
| 73 | + } |
| 74 | + } |
| 75 | + return true; |
| 76 | + } |
| 77 | +} |
0 commit comments