JsonSchema.php
96 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Automattic\WooCommerce\Blueprint\Schemas; |
| 4 | |
| 5 | use Automattic\WooCommerce\Blueprint\UseWPFunctions; |
| 6 | |
| 7 | /** |
| 8 | * Class JsonSchema |
| 9 | */ |
| 10 | class JsonSchema { |
| 11 | use UseWPFunctions; |
| 12 | |
| 13 | /** |
| 14 | * The schema. |
| 15 | * |
| 16 | * @var object The schema. |
| 17 | */ |
| 18 | protected $schema; |
| 19 | |
| 20 | /** |
| 21 | * JsonSchema constructor. |
| 22 | * |
| 23 | * @param string $json_path The path to the JSON file. |
| 24 | * |
| 25 | * @throws \RuntimeException If the JSON file cannot be read. |
| 26 | * @throws \InvalidArgumentException If the JSON is invalid or missing 'steps' field. |
| 27 | */ |
| 28 | public function __construct( $json_path ) { |
| 29 | $real_path = realpath( $json_path ); |
| 30 | |
| 31 | if ( false === $real_path ) { |
| 32 | throw new \InvalidArgumentException( 'Invalid schema path' ); |
| 33 | } |
| 34 | |
| 35 | $contents = $this->wp_filesystem_get_contents( $real_path ); |
| 36 | |
| 37 | if ( false === $contents ) { |
| 38 | throw new \RuntimeException( "Failed to read the JSON file at {$real_path}." ); |
| 39 | } |
| 40 | |
| 41 | $schema = json_decode( $contents ); |
| 42 | $this->schema = $schema; |
| 43 | |
| 44 | if ( ! $this->validate() ) { |
| 45 | throw new \InvalidArgumentException( "Invalid JSON or missing 'steps' field." ); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Returns the steps from the schema. |
| 51 | * |
| 52 | * @return array |
| 53 | */ |
| 54 | public function get_steps() { |
| 55 | return $this->schema->steps; |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Returns steps by name. |
| 60 | * |
| 61 | * @param string $name The name of the step. |
| 62 | * |
| 63 | * @return array |
| 64 | */ |
| 65 | public function get_step( $name ) { |
| 66 | $steps = array(); |
| 67 | foreach ( $this->schema->steps as $step ) { |
| 68 | if ( $step->step === $name ) { |
| 69 | $steps[] = $step; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | return $steps; |
| 74 | } |
| 75 | |
| 76 | /** |
| 77 | * Just makes sure that the JSON contains 'steps' field. |
| 78 | * |
| 79 | * We're going to validate 'steps' later because we can't know the exact schema |
| 80 | * ahead of time. 3rd party plugins can add their step processors. |
| 81 | * |
| 82 | * @return bool[ |
| 83 | */ |
| 84 | public function validate() { |
| 85 | if ( json_last_error() !== JSON_ERROR_NONE ) { |
| 86 | return false; |
| 87 | } |
| 88 | |
| 89 | if ( ! isset( $this->schema->steps ) || ! is_array( $this->schema->steps ) ) { |
| 90 | return false; |
| 91 | } |
| 92 | |
| 93 | return true; |
| 94 | } |
| 95 | } |
| 96 |