Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
96.97% |
32 / 33 |
|
83.33% |
5 / 6 |
CRAP | |
0.00% |
0 / 1 |
| Modifier_Fallback | |
96.97% |
32 / 33 |
|
83.33% |
5 / 6 |
10 | |
0.00% |
0 / 1 |
| add_fallback_parser | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| parse | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
4 | |||
| get_parsers | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| schema | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
1 | |||
| __toString | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| jsonSerialize | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Automattic\Jetpack\Schema\Modifiers; |
| 4 | |
| 5 | use Automattic\Jetpack\Schema\Parser; |
| 6 | use Automattic\Jetpack\Schema\Schema_Error; |
| 7 | use Automattic\Jetpack\Schema\Utils; |
| 8 | |
| 9 | class Modifier_Fallback implements Parser { |
| 10 | private $parsers = array(); |
| 11 | |
| 12 | public function add_fallback_parser( Parser $parser ) { |
| 13 | $this->parsers[] = $parser; |
| 14 | } |
| 15 | |
| 16 | public function parse( $value, $context ) { |
| 17 | $parsers_failed = array(); |
| 18 | foreach ( $this->parsers as $key => $parser ) { |
| 19 | try { |
| 20 | // Attempt to parse the value with the current parser |
| 21 | return $parser->parse( $value, $context ); |
| 22 | } catch ( Schema_Error $error ) { |
| 23 | |
| 24 | if ( Utils::is_debug() ) { |
| 25 | $next_parser = $this->parsers[ $key + 1 ] ?? 'none'; |
| 26 | $data = array( |
| 27 | 'parser' => (string) $parser, |
| 28 | 'next_parser' => (string) $next_parser, |
| 29 | 'parsers_available' => $this->parsers, |
| 30 | ); |
| 31 | $value_type = gettype( $value ); |
| 32 | $context->log( "Fallback($parser): Failed to parse $value_type.", $data, $error ); |
| 33 | } |
| 34 | |
| 35 | $parsers_failed[] = (string) $parser; |
| 36 | continue; |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | $message = 'Failed to parse value using: ' . implode( ' or ', $parsers_failed ); |
| 41 | |
| 42 | // If none of the parsers succeed, throw Schema_Error |
| 43 | throw new Schema_Error( $message, $value ); |
| 44 | } |
| 45 | |
| 46 | public function get_parsers() { |
| 47 | return $this->parsers; |
| 48 | } |
| 49 | |
| 50 | public function schema() { |
| 51 | return array( |
| 52 | 'type' => 'or', |
| 53 | 'value' => array_map( |
| 54 | function ( $parser ) { |
| 55 | return $parser->schema(); |
| 56 | }, |
| 57 | $this->parsers |
| 58 | ), |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | public function __toString() { |
| 63 | $result = array(); |
| 64 | foreach ( $this->parsers as $parser ) { |
| 65 | $result[] = (string) $parser; |
| 66 | } |
| 67 | return implode( ' OR ', $result ); |
| 68 | } |
| 69 | |
| 70 | #[\ReturnTypeWillChange] |
| 71 | public function jsonSerialize() { |
| 72 | return $this->schema(); |
| 73 | } |
| 74 | } |