array-continue-exception.php
2 years ago
array-convert-once.php
2 years ago
array-tools.php
2 years ago
arrayable-once.php
2 years ago
arrayable.php
2 years ago
collection-item-interface.php
2 years ago
collection.php
2 years ago
array-tools.php
67 lines
| 1 | <?php |
| 2 | |
| 3 | |
| 4 | namespace Jet_Form_Builder\Classes\Arrayable; |
| 5 | |
| 6 | use Jet_Form_Builder\Actions\Methods\Post_Modification\Post_Je_Relation_Property; |
| 7 | |
| 8 | class Array_Tools { |
| 9 | |
| 10 | /** |
| 11 | * @param array|\Generator $payload |
| 12 | * |
| 13 | * @return array |
| 14 | */ |
| 15 | public static function to_array( $payload ): array { |
| 16 | if ( $payload instanceof \Generator ) { |
| 17 | return self::from_generator( $payload ); |
| 18 | } |
| 19 | |
| 20 | return self::from_array( $payload ); |
| 21 | } |
| 22 | |
| 23 | public static function from_generator( \Generator $generator ): array { |
| 24 | $response = array(); |
| 25 | |
| 26 | foreach ( $generator as $value ) { |
| 27 | $response[] = $value; |
| 28 | } |
| 29 | |
| 30 | return $response; |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * @param array|Collection $iterator |
| 35 | * |
| 36 | * @return \Generator |
| 37 | */ |
| 38 | public static function reverse( $iterator ): \Generator { |
| 39 | for ( $current = count( $iterator ) - 1; $current >= 0; $current -- ) { |
| 40 | yield $iterator[ $current ]; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | public static function from_array( array $payload ): array { |
| 45 | foreach ( $payload as $index => $object ) { |
| 46 | if ( is_array( $object ) ) { |
| 47 | continue; |
| 48 | } |
| 49 | |
| 50 | /** @var Arrayable $object */ |
| 51 | if ( is_object( $object ) && ! ( $object instanceof Arrayable ) ) { |
| 52 | wp_die( 'Must implements Arrayable.', 'Illegal item of array' ); |
| 53 | } |
| 54 | |
| 55 | try { |
| 56 | $payload[ $index ] = $object->to_array(); |
| 57 | } catch ( Array_Continue_Exception $exception ) { |
| 58 | unset( $payload[ $index ] ); |
| 59 | continue; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | return array_values( $payload ); |
| 64 | } |
| 65 | |
| 66 | } |
| 67 |