-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Remove league/json-guard and replace with opis/json-schema for PHP 8.1 upgrade #723
Comments
How to begin @coderabbitai? |
Tip For best results, initiate chat on the files or code changes. @ThomasAFink, now I can provide a complete migration plan for the Schema Validator. Let's create a new implementation using Opis/json-schema that maintains the same functionality: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\{Validator as OpisValidator, Schema as OpisSchema, ValidationResult};
use Opis\JsonSchema\Errors\ValidationError as OpisValidationError;
class Validator
{
protected $schemaObject;
protected $schemaData;
protected $locale;
protected $validator;
protected $validationResult;
public function __construct($data, Schema $schemaObject, $locale)
{
$this->schemaData = $data;
$this->schemaObject = $schemaObject;
$this->locale = $locale;
$this->validator = new OpisValidator();
// Register custom keywords
$this->validator->resolver()->registerKeyword(
'coerce-type',
new Extensions\CoerceType()
);
// Perform validation
$schema = OpisSchema::fromJsonString(json_encode($schemaObject->toJsonObject()));
$this->validationResult = $this->validator->validate($data, $schema);
}
public function isValid()
{
return $this->validationResult->isValid();
}
public function getErrors()
{
if ($this->isValid()) {
return [];
}
$errorsReducedList = [];
$error = $this->validationResult->getFirstError();
while ($error) {
$errorsReducedList[] = new ValidationError(
$this->getCustomMessage($error),
$error->keyword(),
$error->keywordArgs(),
$error->data(),
$this->getTranslatedPointer($error),
$error->schema(),
$error->schemaPath()
);
$error = $this->validationResult->getNextError();
}
return $errorsReducedList;
}
public function getCustomMessage(OpisValidationError $error)
{
$message = null;
$property = new \BO\Zmsentities\Helper\Property($error->schema());
$message = $property['x-locale'][$this->locale]->messages[$error->keyword()]->get();
return $message ?: $error->message();
}
public static function getOriginPointer(OpisValidationError $error)
{
$pointer = explode('/', $error->schemaPath());
$keys = array_keys($pointer, 'properties', true);
if (0 < count($keys)) {
$pointer = array_values(array_slice($pointer, end($keys) + 1, null, true));
}
return reset($pointer);
}
public function getTranslatedPointer(OpisValidationError $error)
{
$property = new \BO\Zmsentities\Helper\Property($error->schema());
return $property['x-locale'][$this->locale]->pointer->get(static::getOriginPointer($error));
}
public function registerFormatExtension($name, $extension)
{
return $this->validator->resolver()->registerFormat($name, $extension);
}
} And here's the CoerceType extension implementation for Opis: <?php
namespace BO\Zmsentities\Schema\Extensions;
use Opis\JsonSchema\Keyword;
use Opis\JsonSchema\ValidationContext;
use Opis\JsonSchema\Errors\ValidationError;
class CoerceType implements Keyword
{
public function validate($data, ValidationContext $context, $value): ?ValidationError
{
$type = $value;
// Perform type coercion
switch ($type) {
case 'string':
if (is_numeric($data) || is_bool($data)) {
$context->setData((string)$data);
}
break;
case 'number':
if (is_string($data) && is_numeric($data)) {
$context->setData((float)$data);
}
break;
case 'integer':
if (is_string($data) && ctype_digit($data)) {
$context->setData((int)$data);
}
break;
case 'boolean':
if (is_string($data)) {
if ($data === 'true') {
$context->setData(true);
} elseif ($data === 'false') {
$context->setData(false);
}
}
break;
}
return null; // Return null if validation passes
}
} Let's create a unit test to ensure the migration works correctly: <?php
namespace BO\Zmsentities\Tests\Schema;
use PHPUnit\Framework\TestCase;
use BO\Zmsentities\Schema\Validator;
use BO\Zmsentities\Schema\Schema;
class ValidatorTest extends TestCase
{
public function testBasicValidation()
{
$schema = new Schema([
'type' => 'object',
'properties' => [
'name' => [
'type' => 'string',
'x-locale' => [
'en' => [
'messages' => [
'type' => 'Must be a string'
],
'pointer' => 'Name'
]
]
],
'age' => [
'type' => 'integer',
'coerce-type' => 'integer'
]
],
'required' => ['name', 'age']
]);
// Test valid data
$validator = new Validator(['name' => 'John', 'age' => '25'], $schema, 'en');
$this->assertTrue($validator->isValid());
$this->assertEmpty($validator->getErrors());
// Test invalid data
$validator = new Validator(['name' => 123, 'age' => 'invalid'], $schema, 'en');
$this->assertFalse($validator->isValid());
$errors = $validator->getErrors();
$this->assertCount(2, $errors);
}
} Next steps:
Would you like me to:
Let me know which aspect you'd like to focus on next! (_/)/ 🔗 Analysis chainLet me help you get started with replacing Let me analyze the results and provide you with a structured plan to begin the migration. @ThomasAFink, here's a step-by-step plan to begin the migration:
Here's a basic example of how the migration would look: // Old code with league/json-guard
use League\JsonGuard\Validator;
$validator = new Validator($data, $schema);
$isValid = $validator->passes();
// New code with opis/json-schema
use Opis\JsonSchema\{Validator, Schema};
$validator = new Validator();
$schema = Schema::fromJsonString($schemaString);
$result = $validator->validate($data, $schema);
$isValid = $result->isValid(); Would you like me to:
Please let me know which aspect you'd like to focus on first, and I'll provide more specific guidance. (_/)/ Based on the analysis, I can see that @ThomasAFink, here's a detailed migration plan:
Let's start with updating the Schema Validator first. Would you like me to:
Please let me know which aspect you'd like to focus on first, and I'll provide more specific guidance. (_/)/ 🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 20541 Script:
Length of output: 2569 |
Task Description
In the ZMS system, the library
league/json-guard
needs to be removed and replaced withopis/json-schema
. The focus is on the implementation ofJsonSerializable::jsonSerialize()
.Details
Acceptance Criteria
league/json-guard
has been successfully replaced withopis/json-schema
.JsonSerializable::jsonSerialize()
works correctly.Ask @coderabbitai on how to get started.
The text was updated successfully, but these errors were encountered: