# k2gl/entity-exist

> A Symfony validator constraint that asserts an entity exists.

Validate that an id (or composite key) really points at a row, right in your constraint set.

## Install

```bash
composer require k2gl/entity-exist
```

## Requirements

- PHP ^8.1

## Documentation

# Assert an entity exists (or does not) with a Symfony constraint and Doctrine

[![CI](https://img.shields.io/github/actions/workflow/status/k2gl/entity-exist/ci.yml?branch=main&label=CI&logo=github)](https://github.com/k2gl/entity-exist/actions/workflows/ci.yml)
[![Latest Stable Version](https://img.shields.io/packagist/v/k2gl/entity-exist?logo=packagist&logoColor=white)](https://packagist.org/packages/k2gl/entity-exist)
[![Total Downloads](https://img.shields.io/packagist/dt/k2gl/entity-exist?logo=packagist&logoColor=white)](https://packagist.org/packages/k2gl/entity-exist)
[![PHPStan Level](https://img.shields.io/badge/PHPStan-level%209-2a5ea7?logo=php&logoColor=white)](https://phpstan.org)
[![License](https://img.shields.io/packagist/l/k2gl/entity-exist?color=yellowgreen)](https://packagist.org/packages/k2gl/entity-exist)

## Requirements

- PHP 8.1+
- Symfony 6.1, 7.x or 8.x (`symfony/validator`, `symfony/dependency-injection`)
- Doctrine ORM 2.13+ or 3.x

## Installation

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

```
composer require k2gl/entity-exist
```

## Configuration

Makes classes in src/ available to be used as services in **services.yaml**

```
services:
    K2gl\Component\Validator\Constraint\EntityExist\:
        resource: '../vendor/k2gl/entity-exist/src/'
        arguments: ['@doctrine.orm.entity_manager']
        tags:
            - { name: validator.constraint_validator }
```

## Usage

### AssertEntityNotExist

```php
use K2gl\Component\Validator\Constraint\EntityExist\AssertEntityNotExist;

readonly class RegisterUserOrder
{
    public function __construct(
        #[Assert\NotBlank]
        #[Assert\Email]
        #[AssertEntityNotExist(
            entity: User::class,
            property: 'email',
            message: 'User with email "%value%" already registered.'
        )]
        public string $email,
    ) {
    }
}
```

### AssertEntityExist

```php
use K2gl\Component\Validator\Constraint\EntityExist\AssertEntityExist;

readonly class TransferUserToOtherUnitOrder
{
    public function __construct(
        #[Assert\NotBlank]
        #[AssertEntityExist(
            entity: User::class,
            property: 'uuid',
        )]
        public string $user,
        #[Assert\NotBlank]
        #[AssertEntityExist(
            entity: Unit::class,
            property: 'uuid',
        )]
        public string $unit,        
    ) {
    }
}
```

### AssertCompositeEntityExist

A class-level constraint for when fields must reference an existing row **as a
combination** — not each field independently. `AssertEntityExist` on
`warehouseId` and on `companyId` separately would pass as long as each ID
exists somewhere; it can't tell whether the two belong together.

```php
use K2gl\Component\Validator\Constraint\EntityExist\AssertCompositeEntityExist;

#[AssertCompositeEntityExist(
    entity: WarehouseItem::class,
    fields: ['warehouseId', 'companyId'],
)]
readonly class MoveStockOrder
{
    public function __construct(
        public string $warehouseId,
        public string $companyId,
        public int $quantity,
    ) {
    }
}
```

The violation is attached to the first field in `fields` by default; pass
`errorPath` to attach it elsewhere. Validation is skipped if any of the
fields is `null` or an empty string, same as the single-field constraints.

Reads the fields directly off the validated object (public properties, as in
the examples above); no extra service wiring needed — the `services.yaml`
snippet above already covers it.

## Violation codes

Each constraint declares the violation code it emits as a UUID constant on its
own class (`AssertEntityExist::NOT_EXIST`, `AssertEntityNotExist::EXIST`,
`AssertCompositeEntityExist::NOT_EXIST`). Reading those at the call site can be
awkward — especially `AssertEntityNotExist::EXIST`, where the class name and
the constant negate each other.

For nicer reading in error handling and tests, the same codes are also exposed
under neutral names on `ViolationCode`:

```php
use K2gl\Component\Validator\Constraint\EntityExist\ViolationCode;

foreach ($validator->validate($dto) as $violation) {
    if ($violation->getCode() === ViolationCode::ALREADY_EXIST) {
        // handle "entity already exists" case
    }

    if ($violation->getCode() === ViolationCode::NOT_EXIST) {
        // handle "entity not found" case
    }
}
```

`ViolationCode` constants are plain strings that reference the constraint
constants — no duplication, no separate source of truth.

## Pull requests are always welcome
[Collaborate with pull requests](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request)

## API

### K2gl\Component\Validator\Constraint\EntityExist\AssertCompositeEntityExist (class)

- `__construct( public string $entity, public array $fields, public string $message = 'Entity "%entity%" with fields "%fields%": "%values%" does not exist.', public ?string $errorPath = null, ?array $groups = null, mixed $payload = null, )`
- `getTargets(): string`

### K2gl\Component\Validator\Constraint\EntityExist\AssertCompositeEntityExistValidator (class)

- `__construct(private readonly EntityManagerInterface $entityManager)`
- `validate(mixed $value, Constraint $constraint): void`

### K2gl\Component\Validator\Constraint\EntityExist\AssertEntityExist (class)

- `__construct( public string $entity, public string $property = 'id', public string $message = 'Entity "%entity%" with property "%property%": "%value%" does not exist.', ?array $groups = null, mixed $payload = null, )`

### K2gl\Component\Validator\Constraint\EntityExist\AssertEntityExistValidator (class)

- `__construct(private readonly EntityManagerInterface $entityManager)`
- `validate(mixed $value, Constraint $constraint): void`

### K2gl\Component\Validator\Constraint\EntityExist\AssertEntityNotExist (class)

- `__construct( public string $entity, public string $property = 'id', public string $message = 'Entity "%entity%" with property "%property%": "%value%" already exist.', ?array $groups = null, mixed $payload = null, )`

### K2gl\Component\Validator\Constraint\EntityExist\AssertEntityNotExistValidator (class)

- `__construct(private readonly EntityManagerInterface $entityManager)`
- `validate(mixed $value, Constraint $constraint): void`

### K2gl\Component\Validator\Constraint\EntityExist\ViolationCode (class)

_no public methods_

## Links

- GitHub: https://github.com/k2gl/entity-exist
- Packagist: https://packagist.org/packages/k2gl/entity-exist
