-
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 |
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink The test failure is occurring because the public function withLessData()
{
$entity = clone $this;
// Keep only required fields and minimal references
if (isset($entity['process'])) {
$entity['process'] = [
'id' => $entity['process'] instanceof Process ? $entity['process']->getId() : false
];
}
if (isset($entity['scope'])) {
$entity['scope'] = [
'id' => $entity['scope'] instanceof Scope ? $entity['scope']->getId() : null
];
}
if (isset($entity['useraccount'])) {
$entity['useraccount'] = $entity['useraccount'] instanceof Useraccount
? $entity['useraccount']->withLessData()
: new Useraccount($entity['useraccount']);
}
return $entity;
} This implementation:
Would you like me to:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 26921 Script:
Length of output: 9260 ✏️ Learnings added
|
Declaration of CoerceType::validate($data, ValidationContext $context, $value): ValidationError|null must be compatible with Keyword::validate(ValidationContext $context, \Opis\JsonSchema\Schema $schema): ValidationError|nullPHP(PHP2439) Call to unknown method: Opis\JsonSchema\Schema::setData()PHP(PHP0418) in
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation of the CoerceType class: <?php
namespace BO\Zmsentities\Schema\Extensions;
use Opis\JsonSchema\Keyword;
use Opis\JsonSchema\ValidationContext;
use Opis\JsonSchema\Schema;
use Opis\JsonSchema\Errors\ValidationError;
class CoerceType implements Keyword
{
public function validate(ValidationContext $context, Schema $schema): ?ValidationError
{
$data = $context->data();
$type = $schema->data();
// Perform type coercion
switch ($type) {
case 'string':
if (is_numeric($data) || is_bool($data)) {
$context->data = (string)$data;
}
break;
case 'number':
if (is_string($data) && is_numeric($data)) {
$context->data = (float)$data;
}
break;
case 'integer':
if (is_string($data) && ctype_digit($data)) {
$context->data = (int)$data;
}
break;
case 'boolean':
if (is_string($data)) {
if ($data === 'true') {
$context->data = true;
} elseif ($data === 'false') {
$context->data = false;
}
}
break;
}
return null; // Return null if validation passes
}
} Key changes:
✏️ Learnings added
|
Call to unknown method: Opis\JsonSchema\ValidationContext::data()PHP(PHP0418) |
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation of the CoerceType class: <?php
namespace BO\Zmsentities\Schema\Extensions;
use Opis\JsonSchema\Keyword;
use Opis\JsonSchema\ValidationContext;
use Opis\JsonSchema\Schema;
use Opis\JsonSchema\Errors\ValidationError;
class CoerceType implements Keyword
{
public function validate(ValidationContext $context, Schema $schema): ?ValidationError
{
$data = $context->currentData();
$type = $schema->info()->data();
// Perform type coercion
switch ($type) {
case 'string':
if (is_numeric($data) || is_bool($data)) {
$context->setCurrentData((string)$data);
}
break;
case 'number':
if (is_string($data) && is_numeric($data)) {
$context->setCurrentData((float)$data);
}
break;
case 'integer':
if (is_string($data) && ctype_digit($data)) {
$context->setCurrentData((int)$data);
}
break;
case 'boolean':
if (is_string($data)) {
if ($data === 'true') {
$context->setCurrentData(true);
} elseif ($data === 'false') {
$context->setCurrentData(false);
}
}
break;
}
return null; // Return null if validation passes
}
} Key changes:
(_/)/ 🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 98 Script:
Length of output: 18547 ✏️ Learnings added
🧠 Learnings used
|
@coderabbitai Argument '1' passed to __construct() is expected to be of type BO\Zmsentities\Helper\Mixed, Opis\JsonSchema\Schema givenPHP(PHP0406)
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation for the methods using Property: public function getCustomMessage(OpisValidationError $error)
{
$schemaData = $error->schema()->info()->data();
$property = new \BO\Zmsentities\Helper\Property($schemaData);
if (
isset($property['x-locale'][$this->locale]->messages[$error->keyword()])
&& $property['x-locale'][$this->locale]->messages[$error->keyword()] !== null
) {
return $property['x-locale'][$this->locale]->messages[$error->keyword()]->get();
}
return $error->message();
}
public function getTranslatedPointer(OpisValidationError $error)
{
$schemaData = $error->schema()->info()->data();
$property = new \BO\Zmsentities\Helper\Property($schemaData);
if (
isset($property['x-locale'][$this->locale]->pointer)
&& $property['x-locale'][$this->locale]->pointer !== null
) {
return $property['x-locale'][$this->locale]->pointer->get(self::getOriginPointer($error));
}
return self::getOriginPointer($error);
} Key changes:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 13980 ✏️ Learnings added
|
@coderabbitai where is my ddev php docker container version set? |
Tip For best results, initiate chat on the files or code changes. @ThomasAFink The PHP version for your DDEV container is set in php_version: "8.0" You can change it to any supported version (5.6 through 8.3) by modifying this value. For example, to upgrade to PHP 8.1, you would change it to: php_version: "8.1" After changing the version, you'll need to restart your DDEV environment for the changes to take effect. (_/)/ 🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 706 ✏️ Learnings added
|
@coderabbitai I think the $ref no longer works or is different opis/json-schema?
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected Validator implementation for proper $ref resolution: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\{Validator as OpisValidator, ValidationResult, Uri};
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 schema loader for resolving $refs
$baseUri = 'schema://bo/';
$schemaPath = '/var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerPrefix($baseUri, $schemaPath);
// Convert relative refs to absolute URIs
$schemaJson = json_encode($schemaObject->toJsonObject());
$schema = json_decode($schemaJson);
$this->resolveRefs($schema);
$data = json_decode(json_encode($data), false);
$this->validationResult = $this->validator->validate($data, $schema);
}
private function resolveRefs($schema)
{
if (is_object($schema)) {
foreach ($schema as $key => $value) {
if ($key === '$ref' && is_string($value)) {
// Convert relative path to absolute URI
$schema->$key = 'schema://bo/' . $value;
} elseif (is_object($value) || is_array($value)) {
$this->resolveRefs($value);
}
}
} elseif (is_array($schema)) {
foreach ($schema as &$value) {
if (is_object($value) || is_array($value)) {
$this->resolveRefs($value);
}
}
}
}
// ... rest of the methods remain the same ...
} Key changes:
This should fix the $ref resolution issues in the validation process. Would you like me to:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 39897 ✏️ Learnings added
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected Validator implementation for proper $ref resolution: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\{Validator as OpisValidator, ValidationResult, Uri};
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 schema loader with proper base URI
$baseUri = 'file:///var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerFile(
$baseUri,
'/var/www/html/zmsentities/schema/'
);
// Convert schema to JSON and resolve refs
$schemaJson = json_encode($schemaObject->toJsonObject());
$schema = json_decode($schemaJson);
$this->resolveRefs($schema, $baseUri);
// Convert data to JSON object
$data = json_decode(json_encode($data));
$this->validationResult = $this->validator->validate($data, $schema);
}
private function resolveRefs(&$schema, $baseUri)
{
if (is_object($schema)) {
foreach ($schema as $key => &$value) {
if ($key === '$ref' && is_string($value)) {
// Convert relative path to absolute URI
$value = $baseUri . $value;
} elseif (is_object($value) || is_array($value)) {
$this->resolveRefs($value, $baseUri);
}
}
} elseif (is_array($schema)) {
foreach ($schema as &$value) {
if (is_object($value) || is_array($value)) {
$this->resolveRefs($value, $baseUri);
}
}
}
}
// ... rest of the methods remain the same ...
} Key changes:
(_/)/ 🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 39897 ✏️ Learnings added
|
Too many arguments to function validate(). 2 provided, but 0 accepted.PHP(PHP0443) Argument '1' passed to __construct() is expected to be of type BO\Zmsentities\Helper\Mixed, Opis\JsonSchema\Schema givenPHP(PHP0406)
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation for the Validator class: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\{Validator as OpisValidator, ValidationResult, Schema as OpisSchema};
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 schema loader with proper base URI
$baseUri = 'file:///var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerFile(
$baseUri,
'/var/www/html/zmsentities/schema/'
);
// Convert schema to JSON and resolve refs
$schemaJson = json_encode($schemaObject->toJsonObject());
$schema = OpisSchema::fromJsonString($schemaJson);
$this->resolveRefs($schema->info()->data(), $baseUri);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Use schema loader to validate
$this->validationResult = $this->validator->schemaValidation($data, $schema);
}
public function getCustomMessage(OpisValidationError $error)
{
$schemaData = $error->schema()->info()->data();
if (is_object($schemaData)) {
$schemaData = (array)$schemaData;
}
$property = new \BO\Zmsentities\Helper\Property($schemaData);
if (
isset($property['x-locale'][$this->locale]->messages[$error->keyword()])
&& $property['x-locale'][$this->locale]->messages[$error->keyword()] !== null
) {
return $property['x-locale'][$this->locale]->messages[$error->keyword()]->get();
}
return $error->message();
}
public function getTranslatedPointer(OpisValidationError $error)
{
$schemaData = $error->schema()->info()->data();
if (is_object($schemaData)) {
$schemaData = (array)$schemaData;
}
$property = new \BO\Zmsentities\Helper\Property($schemaData);
if (
isset($property['x-locale'][$this->locale]->pointer)
&& $property['x-locale'][$this->locale]->pointer !== null
) {
return $property['x-locale'][$this->locale]->pointer->get(self::getOriginPointer($error));
}
return self::getOriginPointer($error);
}
// ... rest of the methods remain the same ...
} Key changes:
(_/)/ 🔗 Analysis chain@ThomasAFink Here's the corrected implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\{Validator as OpisValidator, ValidationResult, Schema as OpisSchema};
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 schema loader with proper base URI
$baseUri = 'file:///var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerFile(
$baseUri,
'/var/www/html/zmsentities/schema/'
);
// Convert schema to JSON and resolve refs
$schemaJson = json_encode($schemaObject->toJsonObject());
$schema = OpisSchema::fromJsonString($schemaJson);
$this->resolveRefs($schema->resolve(), $baseUri);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Use validateValue instead of validate
$this->validationResult = $this->validator->validateValue($data, $schema);
}
public function getCustomMessage(OpisValidationError $error)
{
$schemaData = $error->schema()->info()->data();
$property = new \BO\Zmsentities\Helper\Property($schemaData);
if (
isset($property['x-locale'][$this->locale]->messages[$error->keyword()])
&& $property['x-locale'][$this->locale]->messages[$error->keyword()] !== null
) {
return $property['x-locale'][$this->locale]->messages[$error->keyword()]->get();
}
return $error->message();
}
public function getTranslatedPointer(OpisValidationError $error)
{
$schemaData = $error->schema()->info()->data();
$property = new \BO\Zmsentities\Helper\Property($schemaData);
if (
isset($property['x-locale'][$this->locale]->pointer)
&& $property['x-locale'][$this->locale]->pointer !== null
) {
return $property['x-locale'][$this->locale]->pointer->get(self::getOriginPointer($error));
}
return self::getOriginPointer($error);
}
// ... rest of the methods remain the same ...
} Key changes:
(_/)/ 🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 14101 ✏️ Learnings added
|
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\{Validator as OpisValidator, 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 schema loader with proper base URI
$baseUri = 'file:///var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerFile(
$baseUri,
'/var/www/html/zmsentities/schema/'
);
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Use schema loader to validate
$this->validationResult = $this->validator->validate($data, $schemaData);
}
// ... rest of the methods remain the same ...
} Key changes:
First, you'll need to add opis/json-schema to your dependencies: composer require opis/json-schema 🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 370 Script:
Length of output: 1908 ✏️ Learnings added
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink First, you need to add opis/json-schema to your dependencies. Run: composer require opis/json-schema:^2.3.0 Here's the corrected Validator implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\{Validator as OpisValidator, 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 schema loader with proper base URI
$baseUri = 'file:///var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerFile(
$baseUri,
'/var/www/html/zmsentities/schema/'
);
// Convert schema to JSON and resolve refs
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
$this->resolveRefs($schemaData, $baseUri);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Use validator directly
$this->validationResult = $this->validator->validate($data, $schemaData);
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
(_/)/ 🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 8729 ✏️ Learnings added
|
@coderabbitai new errors all the same Too many arguments to function validate(). 2 provided, but 0 accepted.PHP(PHP0443)
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation for the Validator class: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\{Validator as OpisValidator, 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 schema loader for the schema:// protocol
$schemaPath = '/var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Resolve all $ref references to use schema:// protocol
$this->resolveRefs($schemaData);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Validate using the resolved schema
$this->validationResult = $this->validator->validate($data, $schemaData);
}
private function resolveRefs(&$schema)
{
if (is_object($schema)) {
foreach ($schema as $key => &$value) {
if ($key === '$ref' && is_string($value)) {
// Convert relative path to schema:// protocol
$value = 'schema://' . $value;
} elseif (is_object($value) || is_array($value)) {
$this->resolveRefs($value);
}
}
} elseif (is_array($schema)) {
foreach ($schema as &$value) {
if (is_object($value) || is_array($value)) {
$this->resolveRefs($value);
}
}
}
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 3609 Script:
Length of output: 2730 ✏️ Learnings added
🧠 Learnings used
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink First, add opis/json-schema to your composer.json: {
"require": {
"opis/json-schema": "^2.3.0"
}
} Then run: composer update Here's the corrected Validator implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\Validator as OpisValidator;
use Opis\JsonSchema\Errors\ValidationError as OpisValidationError;
use Opis\JsonSchema\Helper;
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();
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Register schema loader for resolving $refs
$schemaPath = '/var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
$this->validator->resolver()->registerFile('schema://contact.json', $schemaPath . 'contact.json');
$this->validator->resolver()->registerFile('schema://scope.json', $schemaPath . 'scope.json');
// Validate
$this->validationResult = $this->validator->validate($data, $schemaData);
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
(_/)/ ✏️ Learnings added
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 75424 Script:
Length of output: 1509 🧠 Learnings used
|
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink First, let's install opis/json-schema: composer require opis/json-schema:^2.3.0 Then, here's the corrected Validator implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\Validator as OpisValidator;
use Opis\JsonSchema\Errors\ValidationError as OpisValidationError;
use Opis\JsonSchema\Helper;
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 schema loader for resolving $refs
$schemaPath = '/var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Create validation context and validate
$context = $this->validator->makeContext($data, $schemaData);
$this->validationResult = $context->validate();
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 422 Script:
Length of output: 2971 ✏️ Learnings added
🧠 Learnings used
|
Call to unknown method: League\JsonGuard\Validator|Opis\JsonSchema\Validator::makeContext()PHP(PHP0418)
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink First, let's update your composer.json. Add this to your "opis/json-schema": "^2.3.0" And remove: "league/json-guard": "^1.0" Then run: composer update Here's the corrected Validator implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\Validator as OpisValidator;
use Opis\JsonSchema\Errors\ValidationError as OpisValidationError;
use Opis\JsonSchema\Helper;
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 schema loader for resolving $refs
$schemaPath = '/var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Validate using the schema
$this->validationResult = $this->validator->dataValidation($data, $schemaData);
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 2007 ✏️ Learnings added
🧠 Learnings used
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\Validator as OpisValidator;
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 schema loader for resolving $refs
$schemaPath = '/var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Use validate() method directly
$this->validationResult = $this->validator->validate($data, $schemaData);
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
✏️ Learnings added
🧠 Learnings used
|
@coderabbitai still error
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation for the Validator class: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\Validator as OpisValidator;
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 all schema files individually
$schemaPath = '/var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
// Register common schema files
$commonSchemas = ['process.json', 'apiclient.json', 'scope.json', 'client.json',
'appointment.json', 'queue.json', 'request.json', 'useraccount.json'];
foreach ($commonSchemas as $schema) {
$this->validator->resolver()->registerFile(
'schema://' . $schema,
$schemaPath . $schema
);
}
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Validate using the schema
$this->validationResult = $this->validator->validate($data, $schemaData);
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 19864 ✏️ Learnings added
🧠 Learnings used
|
@coderabbitai is there another solution maybe changing all the "$ref", in the json schemas and fixtures for opis/json-schema? |
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Let's keep the schema files as-is and handle the refs in the Validator class. Here's the corrected implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\Validator as OpisValidator;
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 schema loader for resolving $refs
$schemaPath = '/var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Set max errors to get all validation errors
$this->validator->setMaxErrors(100);
$this->validator->setStopAtFirstError(false);
// Validate using the schema
$this->validationResult = $this->validator->validate($data, $schemaData);
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 91366 ✏️ Learnings added
🧠 Learnings used
|
@coderabbitai this doesn't solve the issue. What are you talking about? My current:
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\Validator as OpisValidator;
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 schema loader for resolving $refs
$schemaPath = '/var/www/html/zmsentities/schema/';
// Register each schema file with its absolute URI
$commonSchemas = [
'process.json', 'apiclient.json', 'scope.json', 'client.json',
'appointment.json', 'queue.json', 'request.json', 'useraccount.json',
'link.json', 'workstation.json'
];
foreach ($commonSchemas as $schema) {
$schemaContent = file_get_contents($schemaPath . $schema);
$this->validator->resolver()->registerRaw(
$schemaContent,
'file://' . $schemaPath . $schema
);
}
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Validate using the schema
$this->validationResult = $this->validator->validate($data, $schemaData);
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 19864 ✏️ Learnings added
🧠 Learnings used
|
@coderabbitai still error
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\Validator as OpisValidator;
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 schema loader for resolving $refs
$schemaPath = '/var/www/html/zmsentities/schema/';
// Register all schema files
$commonSchemas = [
'process.json', 'apiclient.json', 'scope.json', 'client.json',
'appointment.json', 'queue.json', 'request.json', 'useraccount.json',
'link.json', 'workstation.json', 'department.json', 'contact.json',
'provider.json', 'cluster.json', 'day.json', 'availability.json',
'organisation.json', 'mimepart.json'
];
// Register schema loader
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
// Register each schema file
foreach ($commonSchemas as $schema) {
if (file_exists($schemaPath . $schema)) {
$schemaContent = file_get_contents($schemaPath . $schema);
$this->validator->resolver()->registerRaw(
$schemaContent,
'schema://' . $schema
);
}
}
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Set max errors and validate
$this->validator->setMaxErrors(100);
$this->validator->setStopAtFirstError(false);
$this->validationResult = $this->validator->validate($data, $schemaData);
}
// ... rest of the methods remain the same ...
} Key changes:
Would you like me to:
✏️ Learnings added
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 66127 🧠 Learnings used
|
@coderabbitai new diverse errors all slightly different. Here's one example:
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the implementation for withLessData() in the Workstation class: public function withLessData()
{
$entity = clone $this;
// Keep only essential fields
$essentialData = [
'id' => $entity['id'] ?? null,
'name' => $entity['name'] ?? '',
];
// Reduce process to minimal reference
if (isset($entity['process']) && $entity['process'] instanceof Process) {
$essentialData['process'] = [
'id' => $entity['process']->getId()
];
}
// Reduce scope to minimal reference
if (isset($entity['scope']) && $entity['scope'] instanceof Scope) {
$essentialData['scope'] = [
'id' => $entity['scope']->getId()
];
}
// Reduce useraccount to minimal form
if (isset($entity['useraccount'])) {
if ($entity['useraccount'] instanceof Useraccount) {
$essentialData['useraccount'] = $entity['useraccount']->withLessData();
} else {
$essentialData['useraccount'] = new Useraccount($entity['useraccount']);
}
}
// Keep minimal queue settings if present
if (isset($entity['queue'])) {
$essentialData['queue'] = [
'appointmentsOnly' => $entity['queue']['appointmentsOnly'] ?? false,
'clusterEnabled' => $entity['queue']['clusterEnabled'] ?? false
];
}
$entity->exchangeArray($essentialData);
return $entity;
} Key aspects:
Would you like me to:
✏️ Learnings added
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 22569 Script:
Length of output: 17362 🧠 Learnings used
|
@coderabbitai commonSchemas is ugly af. We need to be dynamic
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's a more dynamic implementation: public function __construct($data, Schema $schemaObject, $locale)
{
$this->schemaData = $data;
$this->schemaObject = $schemaObject;
$this->locale = $locale;
$this->validator = new OpisValidator();
// Register schema loader for resolving $refs
$schemaPath = '/var/www/html/zmsentities/schema/';
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
// Register all root-level schema files
$this->registerSchemaFiles($schemaPath);
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Set max errors and validate
$this->validator->setMaxErrors(100);
$this->validator->setStopAtFirstError(false);
$this->validationResult = $this->validator->validate($data, $schemaData);
}
private function registerSchemaFiles(string $schemaPath): void
{
$excludeDirs = ['dereferenced', 'citizenapi'];
foreach (new DirectoryIterator($schemaPath) as $file) {
// Skip directories and non-JSON files
if ($file->isDot() || $file->isDir() || $file->getExtension() !== 'json') {
continue;
}
// Skip files in excluded directories
if (str_contains($file->getPathname(), implode('/', $excludeDirs))) {
continue;
}
$schemaContent = file_get_contents($file->getPathname());
$this->validator->resolver()->registerRaw(
$schemaContent,
'schema://' . $file->getFilename()
);
}
} Key changes:
Would you like me to:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 4260 ✏️ Learnings added
🧠 Learnings used
|
Use of unknown class: 'BO\Zmsentities\Schema\DirectoryIterator'
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's the corrected implementation with the proper import: <?php
namespace BO\Zmsentities\Schema;
use Opis\JsonSchema\{Validator as OpisValidator, ValidationResult, Schema as OpisSchema};
use Opis\JsonSchema\Errors\ValidationError as OpisValidationError;
use DirectoryIterator;
class Validator
{
// ... rest of the class implementation remains the same ...
} Key changes:
Would you like me to:
(_/)/ ✏️ Learnings added
🧠 Learnings used
|
@coderabbitai I'm logging the schema and then the data
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Looking at the validation error and the logged schema/data, there are two issues:
Here's the fix for the Validator class: public function __construct($data, Schema $schemaObject, $locale)
{
$this->schemaData = $data;
$this->schemaObject = $schemaObject;
$this->locale = $locale;
// Create validator with type coercion enabled
$this->validator = new OpisValidator([
'typeCoercion' => true
]);
// Register schema loader for resolving $refs
$schemaPath = '/var/www/html/zmsentities/schema/';
// Register schema loader
$this->validator->resolver()->registerPrefix('schema://', $schemaPath);
// Register all schema files dynamically
foreach (glob($schemaPath . '*.json') as $schemaFile) {
if (!str_contains($schemaFile, '/dereferenced/') && !str_contains($schemaFile, '/citizenapi/')) {
$schemaContent = file_get_contents($schemaFile);
$this->validator->resolver()->registerRaw(
$schemaContent,
'schema://' . basename($schemaFile)
);
}
}
// Convert schema to JSON and create schema object
$schemaJson = json_encode($schemaObject->toJsonObject());
$schemaData = json_decode($schemaJson);
// Convert data to JSON object
$data = json_decode(json_encode($data));
// Set max errors and validate
$this->validator->setMaxErrors(100);
$this->validator->setStopAtFirstError(false);
$this->validationResult = $this->validator->validate($data, $schemaData);
} Key changes:
Would you like me to:
(_/)/ ✏️ Learnings added
🧠 Learnings used
|
@coderabbitai how can I modify this setting? |
Tip For best results, initiate chat on the files or code changes. @ThomasAFink You can enable type coercion by passing options to the OpisValidator constructor: $this->validator = new OpisValidator([
'typeCoercion' => true
]); This will allow string values like "-1" to be automatically converted to their corresponding number types during validation. ✏️ Learnings added
🧠 Learnings used
|
Json guard allows "type": ["array", "object"] But doesn't work with opis/json-schema
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's how to handle multiple types in opis/json-schema: {
"title": "ThinnedProvider",
"anyOf": [
{ "type": "array" },
{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Provider ID"
},
"name": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "Provider name"
},
"lat": {
"anyOf": [
{ "type": "number" },
{ "type": "null" }
],
"description": "Latitude in decimal degrees."
},
"lon": {
"anyOf": [
{ "type": "number" },
{ "type": "null" }
],
"description": "Longitude in decimal degrees."
},
"source": {
"type": "string",
"description": "Data source"
},
"contact": {
"title": "ThinnedContact",
"description": "Represents a simplified contact object for the citizen API.",
"anyOf": [
{ "type": "array" },
{
"type": "object",
"properties": {
"city": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "The city name."
},
"country": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "The country name."
},
"name": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "Optional name field displayed for contact."
},
"postalCode": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "The postal (ZIP) code."
},
"region": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "The region or state name."
},
"street": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "The street name."
},
"streetNumber": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "The house/street number."
}
}
},
{ "type": "null" }
]
}
}
},
{ "type": "null" }
]
} ✏️ Learnings added
🧠 Learnings used
|
Tip For best results, initiate chat on the files or code changes. @ThomasAFink Here's how to fix the schema to work with Opis/json-schema: {
"title": "ThinnedProvider",
"anyOf": [
{ "type": "array" },
{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Provider ID"
},
"name": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "Provider name"
},
"lat": {
"anyOf": [
{ "type": "number" },
{ "type": "null" }
],
"description": "Latitude in decimal degrees."
},
"lon": {
"anyOf": [
{ "type": "number" },
{ "type": "null" }
],
"description": "Longitude in decimal degrees."
},
"source": {
"type": "string",
"description": "Data source"
},
"contact": {
"title": "ThinnedContact",
"description": "Represents a simplified contact object for the citizen API.",
"anyOf": [
{ "type": "array" },
{
"type": "object",
"properties": {
"city": {
"anyOf": [
{ "type": "string" },
{ "type": "null" }
],
"description": "The city name."
}
// ... other properties follow the same pattern
}
},
{ "type": "null" }
]
}
}
},
{ "type": "null" }
]
} Key changes:
Would you like me to:
(_/)/ 🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 71318 ✏️ Learnings added
🧠 Learnings used
|
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: