Skip to content

Instantly share code, notes, and snippets.

@a-yasui
Created December 24, 2019 04:54
Show Gist options
  • Select an option

  • Save a-yasui/97dadb819eb628a43b31a1d41fdb6067 to your computer and use it in GitHub Desktop.

Select an option

Save a-yasui/97dadb819eb628a43b31a1d41fdb6067 to your computer and use it in GitHub Desktop.

Revisions

  1. a-yasui created this gist Dec 24, 2019.
    78 changes: 78 additions & 0 deletions JsonSchemaRule.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    <?php

    namespace App\Rules;

    use Illuminate\Contracts\Validation\Rule;
    use JsonSchema\Validator;


    /**
    * Class JsonSchemaRule
    * @package App\Rules
    *
    * スキーマは https://jsonschema.net/ で作っている
    *
    * example:
    * new JsonSchemaRule('post_request_schema.json'),
    */
    class JsonSchemaRule implements Rule
    {
    /**
    * @var string
    */
    protected $schema_file;

    /**
    * @var
    */
    protected $errors;

    /**
    * JsonSchemaRule constructor.
    * @param string $schema_file
    * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
    */
    public function __construct(string $schema_file)
    {
    $this->schema_file = $file_path;
    if (\File::exists( $this->schema_file ) === false) {
    throw new \RuntimeException( 'Not Found json schema file: ' . $this->schema_file );
    }
    }

    /**
    * Determine if the validation rule passes.
    *
    * @param string $attribute
    * @param mixed $value
    * @return bool
    */
    public function passes($attribute, $value)
    {
    $validator = new Validator();
    $data = \GuzzleHttp\json_decode( $value );

    $validator->validate(
    $data,
    (object)[ '$ref' => 'file://' . $this->schema_file ]
    );

    if ($validator->isValid()) {
    return true;
    }

    $this->errors = $validator->getErrors();
    \Log::info($this->errors);
    return false;
    }

    /**
    * Get the validation error message.
    *
    * @return string
    */
    public function message()
    {
    return 'json unvalid.';
    }
    }