Skip to content

Instantly share code, notes, and snippets.

@a-yasui
Created December 24, 2019 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-yasui/97dadb819eb628a43b31a1d41fdb6067 to your computer and use it in GitHub Desktop.
Save a-yasui/97dadb819eb628a43b31a1d41fdb6067 to your computer and use it in GitHub Desktop.
JsonSchema using Validation rule at Laravel 5.8
<?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