B
B
BonBon Slick2021-01-24 18:41:24
symfony
BonBon Slick, 2021-01-24 18:41:24

ValueObject field validation?

There is an entity User and VO Token.
User->Token Token

has 2, 3 fields.

Token {
public string $token;
public DateTime $validTill;
public string $ip;
}


When a token arrives, Constraints are required for validations
1. whether the token is valid by date. Comparison of the valid_till field with the current date. If that comparison is already in the object.
spoiler
abstract class AbstractDateValidityVO extends AbstractVO {
    use StringHelperTrait;

    protected ?DateTimeImmutable $createdAt;
    protected ?DateTimeImmutable $expireAt;

    /**
     * @throws Exception
     */
    public function __construct() {
        $this->createdAt = new DateTimeImmutable();
        // use minimal time for token among all tokens
        $defaultMinutes = 5;
        $this->expireAt = (new DateTimeImmutable())->add(new DateInterval(sprintf('PT%dM', $defaultMinutes)));
    }

    public function value(): object {
        return (object)get_object_vars($this);
    }

    final public function getCreatedAt(): ?DateTimeImmutable {
        return $this->createdAt;
    }

    final  public function isValid(): bool {
        if (null === $this->getValidTill()) {
            return true;
        }
        return new DateTimeImmutable() < $this->getValidTill();
    }

    final public function getValidTill(): ?DateTimeImmutable {
        return $this->expireAt;
    }
}

2. because the token is bound to the IP, then IdenticalTo is the IP of the token to the request token.
There is a nested validation, most likely with a subquery by type, select a user by token and check the field.
Perhaps someone already has validators for VO fields or who has seen where and can share.

Checks for uniqueness and existence have already been done, if necessary, I can share in the answer to the question.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2021-01-24
@BonBonSlick

If I understand you correctly, then this is not validation. These are business rules. Business rules are checked in the service/handler/entity/VO and if the condition is not met an exception is thrown.
The check is placed where there is all the necessary data. If the VO has all the data to check, you can put the check there. You are talking about a request, then we visit such a check in the Handler.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question