Created
December 24, 2019 04:54
-
-
Save a-yasui/97dadb819eb628a43b31a1d41fdb6067 to your computer and use it in GitHub Desktop.
Revisions
-
a-yasui created this gist
Dec 24, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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.'; } }