Moved custom validators from annotations to attributes

This commit is contained in:
Jan Böhmer 2023-06-11 19:32:15 +02:00
parent e5a14557a2
commit 930adaf439
27 changed files with 50 additions and 148 deletions

View file

@ -104,19 +104,13 @@ abstract class Attachment extends AbstractNamedDBElement
*/
protected ?AttachmentContainingDBElement $element = null;
/**
* @var bool
*/
#[ORM\Column(type: Types::BOOLEAN)]
protected bool $show_in_table = false;
/**
* @var AttachmentType|null
* @Selectable()
*/
#[Assert\NotNull(message: 'validator.attachment.must_not_be_null')]
#[ORM\ManyToOne(targetEntity: 'AttachmentType', inversedBy: 'attachments_with_type')]
#[ORM\JoinColumn(name: 'type_id', nullable: false)]
#[Selectable()]
protected ?AttachmentType $attachment_type = null;
public function __construct()

View file

@ -50,12 +50,10 @@ class AttachmentType extends AbstractStructuralDBElement
#[ORM\JoinColumn(name: 'parent_id')]
protected ?AbstractStructuralDBElement $parent = null;
/**
* @var string
* @ValidFileFilter
*/
#[ORM\Column(type: Types::TEXT)]
#[ValidFileFilter]
protected string $filetype_filter = '';
/**
* @var Collection<int, AttachmentTypeAttachment>
*/

View file

@ -87,16 +87,13 @@ abstract class AbstractStructuralDBElement extends AttachmentContainingDBElement
* We can not define the mapping here, or we will get an exception. Unfortunately we have to do the mapping in the
* subclasses.
*
* @var AbstractStructuralDBElement[]|Collection
* @var Collection<AbstractStructuralDBElement>
*/
#[Groups(['include_children'])]
protected Collection $children;
/**
* @var AbstractStructuralDBElement
* @NoneOfItsChildren()
*/
#[Groups(['include_parents', 'import'])]
#[NoneOfItsChildren]
protected ?AbstractStructuralDBElement $parent = null;
/** @var string[] all names of all parent elements as an array of strings,

View file

@ -41,7 +41,6 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
* This entity describes a lot where parts can be stored.
* It is the connection between a part and its store locations.
*
* @ValidPartLot()
* @see \App\Tests\Entity\Parts\PartLotTest
*/
#[ORM\Entity]
@ -49,6 +48,7 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
#[ORM\Table(name: 'part_lots')]
#[ORM\Index(name: 'part_lots_idx_instock_un_expiration_id_part', columns: ['instock_unknown', 'expiration_date', 'id_part'])]
#[ORM\Index(name: 'part_lots_idx_needs_refill', columns: ['needs_refill'])]
#[ValidPartLot]
class PartLot extends AbstractDBElement implements TimeStampableInterface, NamedElementInterface
{
use TimestampTrait;
@ -77,11 +77,11 @@ class PartLot extends AbstractDBElement implements TimeStampableInterface, Named
/**
* @var Storelocation|null The storelocation of this lot
* @Selectable()
*/
#[Groups(['simple', 'extended', 'full', 'import'])]
#[ORM\ManyToOne(targetEntity: 'Storelocation')]
#[ORM\JoinColumn(name: 'id_store_location')]
#[Selectable()]
protected ?Storelocation $storage_location = null;
/**
@ -334,7 +334,7 @@ class PartLot extends AbstractDBElement implements TimeStampableInterface, Named
//When the storage location sets the owner must match, the part lot owner must match the storage location owner
if ($this->getStorageLocation() && $this->getStorageLocation()->isPartOwnerMustMatch()
&& $this->getStorageLocation()->getOwner() && $this->getOwner() && ($this->getOwner() !== $this->getStorageLocation()->getOwner()
&& $this->owner->getID() !== $this->getStorageLocation()->getOwner()->getID())) {
&& $this->owner->getID() !== $this->getStorageLocation()->getOwner()->getID())) {
$context->buildViolation('validator.part_lot.owner_must_match_storage_location_owner')
->setParameter('%owner_name%', $this->getStorageLocation()->getOwner()->getFullName(true))
->atPath('owner')

View file

@ -62,9 +62,9 @@ trait BasicPropertyTrait
/**
* @var Category|null The category this part belongs too (e.g. Resistors). Use tags, for more complex grouping.
* Every part must have a category.
* @Selectable()
*/
#[Assert\NotNull(message: 'validator.select_valid_category')]
#[Selectable()]
#[Groups(['simple', 'extended', 'full', 'import'])]
#[ORM\ManyToOne(targetEntity: 'Category')]
#[ORM\JoinColumn(name: 'id_category', nullable: false)]
@ -72,11 +72,11 @@ trait BasicPropertyTrait
/**
* @var Footprint|null The footprint of this part (e.g. DIP8)
* @Selectable()
*/
#[Groups(['simple', 'extended', 'full', 'import'])]
#[ORM\ManyToOne(targetEntity: 'Footprint')]
#[ORM\JoinColumn(name: 'id_footprint')]
#[Selectable()]
protected ?Footprint $footprint = null;
/**

View file

@ -37,11 +37,11 @@ trait ManufacturerTrait
{
/**
* @var Manufacturer|null The manufacturer of this part
* @Selectable()
*/
#[Groups(['simple', 'extended', 'full', 'import'])]
#[ORM\ManyToOne(targetEntity: 'Manufacturer')]
#[ORM\JoinColumn(name: 'id_manufacturer')]
#[Selectable()]
protected ?Manufacturer $manufacturer = null;
/**

View file

@ -70,18 +70,18 @@ class Supplier extends AbstractCompany
/**
* @var Currency|null The currency that should be used by default for order informations with this supplier.
* Set to null, to use global base currency.
* @Selectable()
*/
#[ORM\ManyToOne(targetEntity: Currency::class)]
#[ORM\JoinColumn(name: 'default_currency_id')]
#[Selectable()]
protected ?Currency $default_currency = null;
/**
* @var BigDecimal|null the shipping costs that have to be paid, when ordering via this supplier
* @BigDecimalPositiveOrZero()
*/
#[Groups(['extended', 'full', 'import'])]
#[ORM\Column(name: 'shipping_costs', nullable: true, type: 'big_decimal', precision: 11, scale: 5)]
#[BigDecimalPositiveOrZero()]
protected ?BigDecimal $shipping_costs = null;
/**

View file

@ -51,9 +51,9 @@ class Currency extends AbstractStructuralDBElement
/**
* @var BigDecimal|null The exchange rate between this currency and the base currency
* (how many base units the current currency is worth)
* @BigDecimalPositive()
*/
#[ORM\Column(type: 'big_decimal', precision: 11, scale: 5, nullable: true)]
#[BigDecimalPositive()]
protected ?BigDecimal $exchange_rate = null;
/**

View file

@ -53,20 +53,20 @@ class Pricedetail extends AbstractDBElement implements TimeStampableInterface
/**
* @var BigDecimal The price related to the detail. (Given in the selected currency)
* @BigDecimalPositive()
*/
#[Groups(['extended', 'full'])]
#[ORM\Column(type: 'big_decimal', precision: 11, scale: 5)]
#[BigDecimalPositive()]
protected BigDecimal $price;
/**
* @var ?Currency The currency used for the current price information.
* If this is null, the global base unit is assumed.
* @Selectable()
* If this is null, the global base unit is assumed
*/
#[Groups(['extended', 'full', 'import'])]
#[ORM\ManyToOne(targetEntity: 'Currency', inversedBy: 'pricedetails')]
#[ORM\JoinColumn(name: 'id_currency')]
#[Selectable()]
protected ?Currency $currency = null;
/**

View file

@ -96,10 +96,10 @@ class ProjectBOMEntry extends AbstractDBElement
/**
* @var ?Currency The currency for the price of this non-part BOM entry
* @Selectable()
*/
#[ORM\ManyToOne(targetEntity: Currency::class)]
#[ORM\JoinColumn]
#[Selectable]
protected ?Currency $price_currency = null;
public function __construct()

View file

@ -22,6 +22,7 @@ declare(strict_types=1);
namespace App\Entity\UserSystem;
use App\Validator\Constraints\NoLockout;
use Doctrine\DBAL\Types\Types;
use App\Entity\Attachments\GroupAttachment;
use App\Entity\Base\AbstractStructuralDBElement;
@ -41,6 +42,7 @@ use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Table('`groups`')]
#[ORM\Index(name: 'group_idx_name', columns: ['name'])]
#[ORM\Index(name: 'group_idx_parent_name', columns: ['parent_id', 'name'])]
#[NoLockout()]
class Group extends AbstractStructuralDBElement implements HasPermissionsInterface
{
/**
@ -66,6 +68,7 @@ class Group extends AbstractStructuralDBElement implements HasPermissionsInterfa
#[Groups(['extended', 'full', 'import'])]
#[ORM\Column(type: Types::BOOLEAN, name: 'enforce_2fa')]
protected bool $enforce2FA = false;
/**
* @var Collection<int, GroupAttachment>
*/
@ -74,15 +77,13 @@ class Group extends AbstractStructuralDBElement implements HasPermissionsInterfa
#[ORM\OrderBy(['name' => 'ASC'])]
protected Collection $attachments;
/**
* @var PermissionData|null
* @ValidPermission()
*/
#[Groups(['full'])]
#[ORM\Embedded(class: 'PermissionData', columnPrefix: 'permissions_')]
#[ValidPermission()]
protected ?PermissionData $permissions = null;
/** @var Collection<int, GroupParameter>
/**
* @var Collection<int, GroupParameter>
*/
#[Assert\Valid]
#[ORM\OneToMany(targetEntity: GroupParameter::class, mappedBy: 'element', cascade: ['persist', 'remove'], orphanRemoval: true)]

View file

@ -24,6 +24,7 @@ namespace App\Entity\UserSystem;
use App\Repository\UserRepository;
use App\EntityListeners\TreeCacheInvalidationListener;
use App\Validator\Constraints\NoLockout;
use Doctrine\DBAL\Types\Types;
use App\Entity\Attachments\AttachmentContainingDBElement;
use App\Entity\Attachments\UserAttachment;
@ -64,6 +65,7 @@ use Jbtronics\TFAWebauthn\Model\TwoFactorInterface as WebauthnTwoFactorInterface
#[ORM\EntityListeners([TreeCacheInvalidationListener::class])]
#[ORM\Table('`users`')]
#[ORM\Index(name: 'user_idx_username', columns: ['name'])]
#[NoLockout()]
class User extends AttachmentContainingDBElement implements UserInterface, HasPermissionsInterface, TwoFactorInterface,
BackupCodeInterface, TrustedDeviceInterface, WebauthnTwoFactorInterface, PreferredProviderInterface, PasswordAuthenticatedUserInterface, SamlUserInterface
{
@ -83,10 +85,10 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe
/**
* @var string|null The theme
* @ValidTheme()
*/
#[Groups(['full', 'import'])]
#[ORM\Column(type: Types::STRING, name: 'config_theme', nullable: true)]
#[ValidTheme()]
protected ?string $theme = null;
/**
@ -127,11 +129,11 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe
/**
* @var Group|null the group this user belongs to
* DO NOT PUT A fetch eager here! Otherwise, you can not unset the group of a user! This seems to be some kind of bug in doctrine. Maybe this is fixed in future versions.
* @Selectable()
*/
#[Groups(['extended', 'full', 'import'])]
#[ORM\ManyToOne(targetEntity: 'Group', inversedBy: 'users')]
#[ORM\JoinColumn(name: 'group_id')]
#[Selectable]
protected ?Group $group = null;
/**
@ -244,19 +246,16 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe
* Dont use fetch=EAGER here, this will cause problems with setting the currency setting.
* TODO: This is most likely a bug in doctrine/symfony related to the UniqueEntity constraint (it makes a db call).
* TODO: Find a way to use fetch EAGER (this improves performance a bit)
* @Selectable()
*/
#[Groups(['extended', 'full', 'import'])]
#[ORM\ManyToOne(targetEntity: Currency::class)]
#[ORM\JoinColumn(name: 'currency_id')]
#[Selectable]
protected ?Currency $currency = null;
/**
* @var PermissionData|null
* @ValidPermission()
*/
#[Groups(['simple', 'extended', 'full', 'import'])]
#[ORM\Embedded(class: 'PermissionData', columnPrefix: 'permissions_')]
#[ValidPermission()]
protected ?PermissionData $permissions = null;
/**
@ -287,7 +286,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe
*
* @return string
*/
public function __toString()
public function __toString(): string
{
$tmp = $this->isDisabled() ? ' [DISABLED]' : '';

View file

@ -29,9 +29,9 @@ use App\Entity\ProjectSystem\ProjectBOMEntry;
use App\Validator\Constraints\ProjectSystem\ValidProjectBuildRequest;
/**
* @ValidProjectBuildRequest()
* @see \App\Tests\Helpers\Projects\ProjectBuildRequestTest
*/
#[ValidProjectBuildRequest]
final class ProjectBuildRequest
{
private readonly int $number_of_builds;

View file

@ -22,25 +22,11 @@ declare(strict_types=1);
*/
namespace App\Validator\Constraints\BigDecimal;
use Symfony\Component\Validator\Constraints\GreaterThan;
use Symfony\Component\Validator\Constraints\Positive;
/**
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*
* @author Jan Schädlich <jan.schaedlich@sensiolabs.de>
*/
class BigDecimalPositive extends GreaterThan
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class BigDecimalPositive extends Positive
{
use BigNumberConstraintTrait;
public $message = 'This value should be positive.';
public function __construct($options = null)
{
parent::__construct($this->configureNumberConstraintOptions($options));
}
public function validatedBy(): string
{
return BigDecimalGreaterThanValidator::class;

View file

@ -22,25 +22,11 @@ declare(strict_types=1);
*/
namespace App\Validator\Constraints\BigDecimal;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\PositiveOrZero;
/**
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*
* @author Jan Schädlich <jan.schaedlich@sensiolabs.de>
*/
class BigDecimalPositiveOrZero extends GreaterThanOrEqual
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class BigDecimalPositiveOrZero extends PositiveOrZero
{
use BigNumberConstraintTrait;
public $message = 'This value should be either positive or zero.';
public function __construct($options = null)
{
parent::__construct($this->configureNumberConstraintOptions($options));
}
public function validatedBy(): string
{
return BigDecimalGreaterThenOrEqualValidator::class;

View file

@ -1,51 +0,0 @@
<?php
declare(strict_types=1);
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2022 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace App\Validator\Constraints\BigDecimal;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use function is_array;
trait BigNumberConstraintTrait
{
private function configureNumberConstraintOptions($options): array
{
if (null === $options) {
$options = [];
} elseif (!is_array($options)) {
$options = [$this->getDefaultOption() => $options];
}
if (isset($options['propertyPath'])) {
throw new ConstraintDefinitionException(sprintf('The "propertyPath" option of the "%s" constraint cannot be set.', static::class));
}
if (isset($options['value'])) {
throw new ConstraintDefinitionException(sprintf('The "value" option of the "%s" constraint cannot be set.', static::class));
}
$options['value'] = 0;
return $options;
}
}

View file

@ -43,9 +43,7 @@ namespace App\Validator\Constraints\Misc;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class ValidRange extends Constraint
{
public string $message = 'validator.invalid_range';

View file

@ -26,9 +26,8 @@ use Symfony\Component\Validator\Constraint;
/**
* This constraint restricts a user in that way that it can not lock itself out of the user system.
*
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
class NoLockout extends Constraint
{
public string $message = 'validator.noLockout';

View file

@ -34,11 +34,8 @@ use Symfony\Component\Validator\ConstraintValidator;
class NoLockoutValidator extends ConstraintValidator
{
protected array $perm_structure;
public function __construct(protected PermissionManager $resolver, protected Security $security, protected EntityManagerInterface $entityManager)
{
$this->perm_structure = $resolver->getPermissionStructure();
}
/**
@ -71,6 +68,8 @@ class NoLockoutValidator extends ConstraintValidator
) ?? false)) {
$this->context->addViolation($constraint->message);
}
} else {
throw new \LogicException('The NoLockout constraint can only be used on User or Group objects.');
}
}
}

View file

@ -27,9 +27,8 @@ use Symfony\Component\Validator\Constraint;
/**
* Constraints the parent property on StructuralDBElement objects in the way, that neither the object self nor any
* of its children can be assigned.
*
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class NoneOfItsChildren extends Constraint
{
/**

View file

@ -26,9 +26,8 @@ use Symfony\Component\Validator\Constraint;
/**
* This constraint checks that the given ProjectBuildRequest is valid.
*
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
class ValidProjectBuildRequest extends Constraint
{
public function getTargets(): string

View file

@ -27,9 +27,8 @@ use Symfony\Component\Validator\Constraint;
/**
* If a property is marked with this constraint, the choosen value (of type StructuralDBElement)
* must NOT be marked as not selectable.
*
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class Selectable extends Constraint
{
public $message = 'validator.isSelectable';

View file

@ -27,9 +27,8 @@ use Symfony\Component\Validator\Constraints\Url;
/**
* Constraints the field that way that the content is either an url or a path to a builtin ressource (like %FOOTPRINTS%).
*
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class UrlOrBuiltin extends Url
{
/**

View file

@ -27,6 +27,7 @@ use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class ValidFileFilter extends Constraint
{
}

View file

@ -27,9 +27,8 @@ use Symfony\Component\Validator\Constraint;
/**
* A constraint "dummy" to validate the PartLot.
* We need to access services in our Validator, so we can not use a simple callback on PartLot.
*
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
class ValidPartLot extends Constraint
{
public function getTargets(): string

View file

@ -28,8 +28,8 @@ use Symfony\Component\Validator\Constraint;
* A PermissionEmbed object with this annotation will be checked with ValidPermissionValidator.
* That means the alsoSet values of the permission operations are set.
*
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class ValidPermission extends Constraint
{
}

View file

@ -26,8 +26,8 @@ use Symfony\Component\Validator\Constraint;
/**
* A constraint to validate the theme setting of the user.
* @Annotation
*/
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class ValidTheme extends Constraint
{
public string $message = 'validator.selected_theme_is_invalid';