Validate ID tag types. Fixes #725

This commit is contained in:
Michael Stenta 2023-10-09 13:18:11 -04:00
parent 389786ce60
commit 6ed8f3ccec
6 changed files with 69 additions and 2 deletions

View File

@ -7,9 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixes
### Fixed
- [Fix asset_lookup and term_lookup exception messages #731](https://github.com/farmOS/farmOS/pull/731)
- [Prevent saving invalid ID tag types #725](https://github.com/farmOS/farmOS/issues/725)
## [2.2.0] 2023-10-06

View File

@ -26,6 +26,9 @@ function farm_id_tag_entity_base_field_info(EntityTypeInterface $entity_type) {
],
];
$fields['id_tag'] = \Drupal::service('farm_field.factory')->baseFieldDefinition($field_info);
// Add an ID tag type constraint to ID tag fields to ensure valid type.
$fields['id_tag']->addConstraint('IdTagType');
}
return $fields;

View File

@ -0,0 +1,24 @@
<?php
namespace Drupal\farm_id_tag\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* Checks that ID tag type is valid.
*
* @Constraint(
* id = "IdTagType",
* label = @Translation("Valid ID tag type", context = "Validation"),
* )
*/
class IdTagTypeConstraint extends Constraint {
/**
* The default violation message.
*
* @var string
*/
public $message = 'Invalid ID tag type: @type';
}

View File

@ -0,0 +1,27 @@
<?php
namespace Drupal\farm_id_tag\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the IdTagTypeConstraint constraint.
*/
class IdTagTypeConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
if (empty($value->type)) {
return;
}
$bundle = $value->getEntity()->bundle();
$valid_types = array_keys(farm_id_tag_type_options($bundle));
if (!in_array($value->type, $valid_types)) {
$this->context->addViolation($constraint->message, ['@type' => $value->type]);
}
}
}

View File

@ -78,6 +78,18 @@ class IdTagTest extends KernelTestBase {
]);
$violations = $asset->validate();
$this->assertEmpty($violations);
// Confirm that an invalid tag type does not pass validation.
$asset = Asset::create([
'name' => $this->randomString(),
'type' => 'test',
'id_tag' => [
'type' => 'invalid',
],
]);
$violations = $asset->validate();
$this->assertNotEmpty($violations);
$this->assertEquals('Invalid ID tag type: invalid', $violations[0]->getMessage());
}
}

View File

@ -27,7 +27,7 @@ class AssetCsvImportTest extends CsvImportTestBase {
*/
public function setUp(): void {
parent::setUp();
$this->installConfig(['farm_equipment']);
$this->installConfig(['farm_id_tag', 'farm_equipment']);
// Add an asset to test parent relationship.
$asset = Asset::create(['name' => 'Test parent', 'type' => 'equipment', 'status' => 'active']);