Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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