Created
December 24, 2019 04:54
-
-
Save a-yasui/97dadb819eb628a43b31a1d41fdb6067 to your computer and use it in GitHub Desktop.
JsonSchema using Validation rule at Laravel 5.8
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 characters
<?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.'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment