RouteParamBag.php
71 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPDesk\FCF\Free\Collections; |
| 4 | |
| 5 | use Doctrine\Common\Collections\ArrayCollection; |
| 6 | use WPDesk\FCF\Free\Exception\UnexpectedParamException; |
| 7 | |
| 8 | /** |
| 9 | * Route Parameters as collection. |
| 10 | * |
| 11 | * @template TKey of string |
| 12 | * @template T |
| 13 | * @extends ArrayCollection<TKey, T> |
| 14 | */ |
| 15 | class RouteParamBag extends ArrayCollection { |
| 16 | |
| 17 | /** |
| 18 | * Returns the nested array as collection. |
| 19 | * |
| 20 | * @param string $key |
| 21 | * @throws UnexpectedParamException |
| 22 | * |
| 23 | * @return RouteParamBag<TKey, T> |
| 24 | */ |
| 25 | public function collection( string $key ): RouteParamBag { |
| 26 | if ( ! is_array( $this->get( $key ) ) ) { |
| 27 | throw new UnexpectedParamException( |
| 28 | sprintf( |
| 29 | 'Parameter "%s" is not an array.', |
| 30 | $key |
| 31 | ) |
| 32 | ); |
| 33 | } |
| 34 | |
| 35 | return new static( $this->get( $key ) ); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Returns the parameter as string. |
| 40 | * |
| 41 | * @param string $key |
| 42 | * @throws UnexpectedParamException |
| 43 | * |
| 44 | * @return string |
| 45 | */ |
| 46 | public function getString( string $key ): string { |
| 47 | $value = $this->get( $key ); |
| 48 | if ( ! \is_scalar( $value ) && ! $value instanceof \Stringable ) { |
| 49 | throw new UnexpectedParamException( |
| 50 | sprintf( |
| 51 | 'Parameter value "%s" cannot be converted to "string".', |
| 52 | $key |
| 53 | ) |
| 54 | ); |
| 55 | } |
| 56 | |
| 57 | return (string) $value; |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Reduce the array to a single value using a callback function. |
| 62 | * |
| 63 | * @param \Closure $callback The callback function to apply |
| 64 | * @param mixed $initial The initial value |
| 65 | * @return mixed The single value resulting from the reduction |
| 66 | */ |
| 67 | public function reduce( \Closure $callback, $initial = null ) { |
| 68 | return array_reduce( $this->toArray(), $callback, $initial ); |
| 69 | } |
| 70 | } |
| 71 |