feat(sites) : brique fondatrice du module Sites (ticket 1/4)
Module Sites optionnel et desactivable via config/modules.php. Entite Site (nom unique, ville, CP FR, couleur hex, adresse), repository + impl Doctrine, migration racine (namespace DoctrineMigrations conforme exception CLAUDE.md), fixtures idempotentes (Chatellerault, Saint-Jean, Pommevic), permissions RBAC sites.view/sites.manage. Tests unitaires + validation via KernelTestCase (UniqueEntity, regex hex et CP, NotBlank, Length). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -3,8 +3,10 @@
|
||||
declare(strict_types=1);
|
||||
use App\Module\Commercial\CommercialModule;
|
||||
use App\Module\Core\CoreModule;
|
||||
use App\Module\Sites\SitesModule;
|
||||
|
||||
return [
|
||||
CoreModule::class,
|
||||
CommercialModule::class,
|
||||
SitesModule::class,
|
||||
];
|
||||
|
||||
@@ -15,6 +15,16 @@ doctrine:
|
||||
dir: '%kernel.project_dir%/src/Module/Core/Domain/Entity'
|
||||
prefix: 'App\Module\Core\Domain\Entity'
|
||||
alias: Core
|
||||
# Mapping inconditionnelle du module Sites : la structure DB
|
||||
# existe meme si SitesModule::class est retire de config/modules.php.
|
||||
# L'activation fonctionnelle (ex: exposition des permissions, futurs
|
||||
# endpoints API) passe exclusivement par config/modules.php.
|
||||
Sites:
|
||||
type: attribute
|
||||
is_bundle: false
|
||||
dir: '%kernel.project_dir%/src/Module/Sites/Domain/Entity'
|
||||
prefix: 'App\Module\Sites\Domain\Entity'
|
||||
alias: Sites
|
||||
controller_resolver:
|
||||
auto_mapping: false
|
||||
|
||||
|
||||
@@ -24,3 +24,6 @@ services:
|
||||
|
||||
App\Module\Core\Domain\Repository\UserRepositoryInterface:
|
||||
alias: App\Module\Core\Infrastructure\Doctrine\DoctrineUserRepository
|
||||
|
||||
App\Module\Sites\Domain\Repository\SiteRepositoryInterface:
|
||||
alias: App\Module\Sites\Infrastructure\Doctrine\DoctrineSiteRepository
|
||||
|
||||
67
migrations/Version20260417120000.php
Normal file
67
migrations/Version20260417120000.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Module Sites - Ticket 1/4 : brique fondatrice de donnees.
|
||||
*
|
||||
* Cree la table `site` qui porte les etablissements physiques de l'instance
|
||||
* Coltura. La table est creee inconditionnellement : meme si SitesModule est
|
||||
* desactive dans `config/modules.php`, la structure DB existe (pas de
|
||||
* dependance dure depuis Core, mais pas de coin d'ombre schema non plus).
|
||||
*
|
||||
* Note sur l'emplacement du fichier :
|
||||
* Par convention projet les migrations vivent dans
|
||||
* `src/Module/{Module}/Infrastructure/Doctrine/Migrations/`, sauf pour les
|
||||
* initialisations critiques. Cf. CLAUDE.md (section "Regles d'architecture")
|
||||
* qui documente le bug de tri alphabetique de Doctrine Migrations 3.x avec
|
||||
* plusieurs `migrations_paths` : tant que ce n'est pas corrige, toute
|
||||
* migration d'initialisation (creation de table sur base vide) reste au
|
||||
* namespace racine `DoctrineMigrations` dans `migrations/`.
|
||||
*/
|
||||
final class Version20260417120000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Module Sites : creation de la table site (nom, ville, cp, couleur, adresse complete, timestamps).';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
// Creation de la table site. Toutes les colonnes sont NOT NULL :
|
||||
// - le champ `color` est contraint cote applicatif au format #RRGGBB
|
||||
// (7 caracteres), la longueur DB est dimensionnee en consequence ;
|
||||
// - `postal_code` est limite a 10 caracteres pour laisser marge a
|
||||
// d'eventuels formats etrangers plus tard, tout en le validant
|
||||
// strictement en 5 chiffres cote applicatif (format FR).
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE site (
|
||||
id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
city VARCHAR(100) NOT NULL,
|
||||
postal_code VARCHAR(10) NOT NULL,
|
||||
color VARCHAR(7) NOT NULL,
|
||||
full_address TEXT NOT NULL,
|
||||
created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
)
|
||||
SQL);
|
||||
|
||||
// Index unique sur le nom : garantit l'invariant metier "un site porte
|
||||
// un nom unique" et permet a la contrainte UniqueEntity cote Symfony
|
||||
// de s'appuyer sur une erreur DB en cas de race condition.
|
||||
$this->addSql('CREATE UNIQUE INDEX uniq_site_name ON site (name)');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// Drop direct : aucune FK depuis/vers la table dans ce ticket.
|
||||
$this->addSql('DROP TABLE site');
|
||||
}
|
||||
}
|
||||
185
src/Module/Sites/Domain/Entity/Site.php
Normal file
185
src/Module/Sites/Domain/Entity/Site.php
Normal file
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Sites\Domain\Entity;
|
||||
|
||||
use App\Module\Sites\Infrastructure\Doctrine\DoctrineSiteRepository;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
* Site physique (usine / etablissement) appartenant a l'instance Coltura.
|
||||
*
|
||||
* Brique fondatrice du module Sites : cette entite n'est pas exposee par
|
||||
* une ressource API Platform dans ce ticket (ticket 1/4). Elle sert de socle
|
||||
* de donnees aux tickets suivants (rattachement utilisateurs, affichage
|
||||
* navbar, etc.). Aucune dependance dure depuis le module Core : la table
|
||||
* est creee meme si le module est desactive (voir migration dediee).
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: DoctrineSiteRepository::class)]
|
||||
#[ORM\Table(name: 'site')]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_site_name', columns: ['name'])]
|
||||
#[ORM\HasLifecycleCallbacks]
|
||||
#[UniqueEntity(fields: ['name'], message: 'Un site avec ce nom existe deja.')]
|
||||
class Site
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(length: 100)]
|
||||
#[Assert\NotBlank(message: 'Le nom du site est requis.')]
|
||||
#[Assert\Length(max: 100, maxMessage: 'Le nom du site ne peut pas depasser {{ limit }} caracteres.')]
|
||||
private string $name;
|
||||
|
||||
#[ORM\Column(length: 100)]
|
||||
#[Assert\NotBlank(message: 'La ville du site est requise.')]
|
||||
#[Assert\Length(max: 100, maxMessage: 'La ville ne peut pas depasser {{ limit }} caracteres.')]
|
||||
private string $city;
|
||||
|
||||
// Colonne mappee sur le snake_case PostgreSQL (convention projet : noms de
|
||||
// colonnes en minuscules dans le SQL brut). Le format est contraint au
|
||||
// code postal francais strict : 5 chiffres numeriques.
|
||||
#[ORM\Column(name: 'postal_code', length: 10)]
|
||||
#[Assert\NotBlank(message: 'Le code postal est requis.')]
|
||||
#[Assert\Length(max: 10, maxMessage: 'Le code postal ne peut pas depasser {{ limit }} caracteres.')]
|
||||
#[Assert\Regex(
|
||||
pattern: '/^\d{5}$/',
|
||||
message: 'Le code postal doit etre compose de 5 chiffres (format FR).',
|
||||
)]
|
||||
private string $postalCode;
|
||||
|
||||
// Couleur d'identification visuelle du site au format hex #RRGGBB (7 chars
|
||||
// incluant le diese). Utilisee plus tard par la navbar (ticket 3) pour
|
||||
// distinguer les sites d'un coup d'oeil.
|
||||
#[ORM\Column(length: 7)]
|
||||
#[Assert\NotBlank(message: 'La couleur est requise.')]
|
||||
#[Assert\Regex(
|
||||
pattern: '/^#[0-9A-Fa-f]{6}$/',
|
||||
message: 'La couleur doit etre un code hex de 7 caracteres au format #RRGGBB.',
|
||||
)]
|
||||
private string $color;
|
||||
|
||||
// Champ TEXT volontaire : l'adresse complete peut courir sur plusieurs
|
||||
// lignes (voie + complement + mention particuliere). Borne haute a 500
|
||||
// caracteres : une adresse francaise complete tient tres largement dans
|
||||
// cette enveloppe, et la limite applicative protege contre les payloads
|
||||
// anormalement volumineux envoyes par un client (garde DoS basique).
|
||||
#[ORM\Column(name: 'full_address', type: Types::TEXT)]
|
||||
#[Assert\NotBlank(message: 'L\'adresse complete est requise.')]
|
||||
#[Assert\Length(max: 500, maxMessage: 'L\'adresse complete ne peut pas depasser {{ limit }} caracteres.')]
|
||||
private string $fullAddress;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: Types::DATETIME_IMMUTABLE)]
|
||||
private DateTimeImmutable $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: Types::DATETIME_IMMUTABLE)]
|
||||
private DateTimeImmutable $updatedAt;
|
||||
|
||||
public function __construct(
|
||||
string $name,
|
||||
string $city,
|
||||
string $postalCode,
|
||||
string $color,
|
||||
string $fullAddress,
|
||||
) {
|
||||
$this->name = $name;
|
||||
$this->city = $city;
|
||||
$this->postalCode = $postalCode;
|
||||
$this->color = $color;
|
||||
$this->fullAddress = $fullAddress;
|
||||
$now = new DateTimeImmutable();
|
||||
$this->createdAt = $now;
|
||||
$this->updatedAt = $now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback Doctrine : a chaque update en base on rafraichit updatedAt.
|
||||
* Ne pas toucher a createdAt ici (immutable apres creation).
|
||||
*/
|
||||
#[ORM\PreUpdate]
|
||||
public function onPreUpdate(): void
|
||||
{
|
||||
$this->updatedAt = new DateTimeImmutable();
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function setName(string $name): static
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCity(): string
|
||||
{
|
||||
return $this->city;
|
||||
}
|
||||
|
||||
public function setCity(string $city): static
|
||||
{
|
||||
$this->city = $city;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPostalCode(): string
|
||||
{
|
||||
return $this->postalCode;
|
||||
}
|
||||
|
||||
public function setPostalCode(string $postalCode): static
|
||||
{
|
||||
$this->postalCode = $postalCode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return $this->color;
|
||||
}
|
||||
|
||||
public function setColor(string $color): static
|
||||
{
|
||||
$this->color = $color;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getFullAddress(): string
|
||||
{
|
||||
return $this->fullAddress;
|
||||
}
|
||||
|
||||
public function setFullAddress(string $fullAddress): static
|
||||
{
|
||||
$this->fullAddress = $fullAddress;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCreatedAt(): DateTimeImmutable
|
||||
{
|
||||
return $this->createdAt;
|
||||
}
|
||||
|
||||
public function getUpdatedAt(): DateTimeImmutable
|
||||
{
|
||||
return $this->updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Sites\Domain\Repository;
|
||||
|
||||
use App\Module\Sites\Domain\Entity\Site;
|
||||
|
||||
interface SiteRepositoryInterface
|
||||
{
|
||||
public function findById(int $id): ?Site;
|
||||
|
||||
public function findByName(string $name): ?Site;
|
||||
|
||||
/**
|
||||
* @return list<Site>
|
||||
*/
|
||||
public function findAllOrderedByName(): array;
|
||||
|
||||
public function save(Site $site): void;
|
||||
|
||||
public function remove(Site $site): void;
|
||||
}
|
||||
105
src/Module/Sites/Infrastructure/DataFixtures/SitesFixtures.php
Normal file
105
src/Module/Sites/Infrastructure/DataFixtures/SitesFixtures.php
Normal file
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Sites\Infrastructure\DataFixtures;
|
||||
|
||||
use App\Module\Sites\Domain\Entity\Site;
|
||||
use App\Module\Sites\Domain\Repository\SiteRepositoryInterface;
|
||||
use Doctrine\Bundle\FixturesBundle\Fixture;
|
||||
use Doctrine\Persistence\ObjectManager;
|
||||
|
||||
/**
|
||||
* Fixtures du module Sites : 3 etablissements de demonstration utilises par
|
||||
* les tickets suivants (rattachement utilisateurs, navbar, etc.).
|
||||
*
|
||||
* Idempotence supportee : le purger Doctrine (ORMPurger) vide la table
|
||||
* `site` avant chaque `doctrine:fixtures:load`. Si le purger est
|
||||
* desactive et la fixture rejouee telle quelle sur une base deja seedee,
|
||||
* le lookup par nom evite le doublon et re-aligne les autres champs.
|
||||
*
|
||||
* Idempotence NON supportee :
|
||||
* - chargement cumulatif apres qu'une autre fixture ait persiste (sans
|
||||
* flush) des Site dans la meme session : `findByName()` s'appuie sur
|
||||
* `findOneBy`, qui n'inspecte pas les entites en attente dans l'unit-of-work
|
||||
* et peut renvoyer null alors qu'un homonyme est deja manage ;
|
||||
* - renommage d'un site : le nom etant la cle de lookup, modifier
|
||||
* `name` dans cette fixture cree un nouveau site et laisse l'ancien
|
||||
* en base (purger desactive). Les autres champs (city, color, etc.)
|
||||
* sont en revanche bien re-synchronises pour un site retrouve.
|
||||
*/
|
||||
class SitesFixtures extends Fixture
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SiteRepositoryInterface $siteRepository,
|
||||
) {}
|
||||
|
||||
public function load(ObjectManager $manager): void
|
||||
{
|
||||
// Chatellerault : couleur imposee par le ticket (bleu Coltura).
|
||||
$this->ensureSite(
|
||||
$manager,
|
||||
name: 'Chatellerault',
|
||||
city: 'Chatellerault',
|
||||
postalCode: '86100',
|
||||
color: '#056CF2',
|
||||
fullAddress: "1 avenue de l'Europe\n86100 Chatellerault",
|
||||
);
|
||||
|
||||
// Saint-Jean : vert emeraude pour contraster avec le bleu Chatellerault.
|
||||
$this->ensureSite(
|
||||
$manager,
|
||||
name: 'Saint-Jean',
|
||||
city: 'Saint-Jean-de-Sauves',
|
||||
postalCode: '86330',
|
||||
color: '#10B981',
|
||||
fullAddress: "12 route de Poitiers\n86330 Saint-Jean-de-Sauves",
|
||||
);
|
||||
|
||||
// Pommevic : ambre pour une troisieme teinte nettement distincte.
|
||||
$this->ensureSite(
|
||||
$manager,
|
||||
name: 'Pommevic',
|
||||
city: 'Pommevic',
|
||||
postalCode: '82400',
|
||||
color: '#F59E0B',
|
||||
fullAddress: "5 chemin des Peupliers\n82400 Pommevic",
|
||||
);
|
||||
|
||||
$manager->flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cree le site s'il n'existe pas encore, sinon re-aligne ville, code
|
||||
* postal, couleur et adresse sur les valeurs de reference.
|
||||
*
|
||||
* Note : le nom sert de cle de lookup (il est unique en base) et n'est
|
||||
* donc pas resynchronise. Consequence : renommer un site dans la
|
||||
* fixture cree un nouveau site sans supprimer l'ancien, sauf si le
|
||||
* purger Doctrine est actif (cas nominal de `doctrine:fixtures:load`).
|
||||
*/
|
||||
private function ensureSite(
|
||||
ObjectManager $manager,
|
||||
string $name,
|
||||
string $city,
|
||||
string $postalCode,
|
||||
string $color,
|
||||
string $fullAddress,
|
||||
): Site {
|
||||
$site = $this->siteRepository->findByName($name);
|
||||
|
||||
if (null === $site) {
|
||||
$site = new Site($name, $city, $postalCode, $color, $fullAddress);
|
||||
$manager->persist($site);
|
||||
|
||||
return $site;
|
||||
}
|
||||
|
||||
$site->setCity($city);
|
||||
$site->setPostalCode($postalCode);
|
||||
$site->setColor($color);
|
||||
$site->setFullAddress($fullAddress);
|
||||
|
||||
return $site;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Sites\Infrastructure\Doctrine;
|
||||
|
||||
use App\Module\Sites\Domain\Entity\Site;
|
||||
use App\Module\Sites\Domain\Repository\SiteRepositoryInterface;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<Site>
|
||||
*/
|
||||
class DoctrineSiteRepository extends ServiceEntityRepository implements SiteRepositoryInterface
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, Site::class);
|
||||
}
|
||||
|
||||
public function findById(int $id): ?Site
|
||||
{
|
||||
return $this->find($id);
|
||||
}
|
||||
|
||||
public function findByName(string $name): ?Site
|
||||
{
|
||||
return $this->findOneBy(['name' => $name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<Site>
|
||||
*/
|
||||
public function findAllOrderedByName(): array
|
||||
{
|
||||
/** @var list<Site> $sites */
|
||||
return $this->findBy([], ['name' => 'ASC']);
|
||||
}
|
||||
|
||||
public function save(Site $site): void
|
||||
{
|
||||
$this->getEntityManager()->persist($site);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
|
||||
public function remove(Site $site): void
|
||||
{
|
||||
$this->getEntityManager()->remove($site);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
37
src/Module/Sites/SitesModule.php
Normal file
37
src/Module/Sites/SitesModule.php
Normal file
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Sites;
|
||||
|
||||
final class SitesModule
|
||||
{
|
||||
public const string ID = 'sites';
|
||||
public const string LABEL = 'Sites';
|
||||
public const bool REQUIRED = false;
|
||||
|
||||
/**
|
||||
* Liste declarative des permissions RBAC exposees par le module Sites.
|
||||
*
|
||||
* Consommee par la commande `app:sync-permissions` (SyncPermissionsCommand)
|
||||
* qui se charge d'upserter ces entrees dans la table `permission`, de
|
||||
* reactiver les codes precedemment marques orphelins et de marquer comme
|
||||
* orphelins ceux qui ont disparu du code source.
|
||||
*
|
||||
* La cle `module` est auto-injectee par le sync command a partir de
|
||||
* `self::ID`, il est donc inutile de la repeter dans chaque entree.
|
||||
*
|
||||
* Convention de nommage des codes : `module.resource[.sub].action` en
|
||||
* snake_case, le prefixe module devant correspondre exactement a
|
||||
* `self::ID` (verifie par la commande de synchronisation).
|
||||
*
|
||||
* @return array<int, array{code: string, label: string}>
|
||||
*/
|
||||
public static function permissions(): array
|
||||
{
|
||||
return [
|
||||
['code' => 'sites.view', 'label' => 'Voir les sites'],
|
||||
['code' => 'sites.manage', 'label' => 'Gerer les sites (creer, editer, supprimer)'],
|
||||
];
|
||||
}
|
||||
}
|
||||
86
tests/Module/Sites/Domain/Entity/SiteTest.php
Normal file
86
tests/Module/Sites/Domain/Entity/SiteTest.php
Normal file
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Sites\Domain\Entity;
|
||||
|
||||
use App\Module\Sites\Domain\Entity\Site;
|
||||
use DateTimeImmutable;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use ReflectionClass;
|
||||
|
||||
/**
|
||||
* Tests unitaires de comportement de l'entite Site : etat initial, setters
|
||||
* et gestion des timestamps. Les contraintes de validation (regex, unicite)
|
||||
* sont couvertes par SiteValidationTest.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class SiteTest extends TestCase
|
||||
{
|
||||
public function testConstructorInitialState(): void
|
||||
{
|
||||
$site = new Site(
|
||||
'Chatellerault',
|
||||
'Chatellerault',
|
||||
'86100',
|
||||
'#056CF2',
|
||||
"1 avenue de l'Europe\n86100 Chatellerault",
|
||||
);
|
||||
|
||||
self::assertNull($site->getId());
|
||||
self::assertSame('Chatellerault', $site->getName());
|
||||
self::assertSame('Chatellerault', $site->getCity());
|
||||
self::assertSame('86100', $site->getPostalCode());
|
||||
self::assertSame('#056CF2', $site->getColor());
|
||||
self::assertStringContainsString('Chatellerault', $site->getFullAddress());
|
||||
self::assertInstanceOf(DateTimeImmutable::class, $site->getCreatedAt());
|
||||
self::assertInstanceOf(DateTimeImmutable::class, $site->getUpdatedAt());
|
||||
}
|
||||
|
||||
public function testCreatedAtAndUpdatedAtAreInitiallyEqual(): void
|
||||
{
|
||||
$site = new Site('A', 'B', '12345', '#000000', 'Rue X');
|
||||
|
||||
// A la creation, les deux timestamps sont seedes avec la meme valeur
|
||||
// pour garantir updated_at >= created_at au niveau base.
|
||||
self::assertEquals($site->getCreatedAt(), $site->getUpdatedAt());
|
||||
}
|
||||
|
||||
public function testOnPreUpdateAdvancesUpdatedAtOnly(): void
|
||||
{
|
||||
$site = new Site('A', 'B', '12345', '#000000', 'Rue X');
|
||||
$originalCreatedAt = $site->getCreatedAt();
|
||||
|
||||
// On force updatedAt a une valeur strictement anterieure via reflection
|
||||
// pour ne pas dependre d'un `sleep()` (flaky en CI, lent) : l'entite
|
||||
// n'expose volontairement pas de setter sur updatedAt, c'est le
|
||||
// callback Doctrine PreUpdate qui s'en charge.
|
||||
$pastUpdatedAt = new DateTimeImmutable('-1 hour');
|
||||
$reflection = new ReflectionClass(Site::class);
|
||||
$updatedAtProperty = $reflection->getProperty('updatedAt');
|
||||
$updatedAtProperty->setValue($site, $pastUpdatedAt);
|
||||
|
||||
$site->onPreUpdate();
|
||||
|
||||
self::assertSame($originalCreatedAt, $site->getCreatedAt(), 'created_at doit rester immuable apres un update.');
|
||||
self::assertGreaterThan($pastUpdatedAt, $site->getUpdatedAt(), 'updated_at doit avancer apres onPreUpdate().');
|
||||
}
|
||||
|
||||
public function testSettersMutateFields(): void
|
||||
{
|
||||
$site = new Site('Old', 'OldCity', '12345', '#000000', 'Old Addr');
|
||||
|
||||
$site->setName('New');
|
||||
$site->setCity('NewCity');
|
||||
$site->setPostalCode('67890');
|
||||
$site->setColor('#ABCDEF');
|
||||
$site->setFullAddress('New Addr');
|
||||
|
||||
self::assertSame('New', $site->getName());
|
||||
self::assertSame('NewCity', $site->getCity());
|
||||
self::assertSame('67890', $site->getPostalCode());
|
||||
self::assertSame('#ABCDEF', $site->getColor());
|
||||
self::assertSame('New Addr', $site->getFullAddress());
|
||||
}
|
||||
}
|
||||
259
tests/Module/Sites/Domain/Entity/SiteValidationTest.php
Normal file
259
tests/Module/Sites/Domain/Entity/SiteValidationTest.php
Normal file
@@ -0,0 +1,259 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Sites\Domain\Entity;
|
||||
|
||||
use App\Module\Sites\Domain\Entity\Site;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
|
||||
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
|
||||
use Symfony\Component\Validator\Validator\ValidatorInterface;
|
||||
|
||||
/**
|
||||
* Tests de validation de l'entite Site : contraintes scalaires (regex couleur
|
||||
* hex, regex code postal FR, NotBlank, Length) ET unicite du nom. Utilise le
|
||||
* validator applicatif (via KernelTestCase) afin que la contrainte
|
||||
* UniqueEntity, adossee a Doctrine, puisse reellement interroger la base de
|
||||
* test.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class SiteValidationTest extends KernelTestCase
|
||||
{
|
||||
private ValidatorInterface $validator;
|
||||
private EntityManagerInterface $em;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
self::bootKernel();
|
||||
$container = self::getContainer();
|
||||
|
||||
/** @var ValidatorInterface $validator */
|
||||
$validator = $container->get(ValidatorInterface::class);
|
||||
$this->validator = $validator;
|
||||
|
||||
/** @var EntityManagerInterface $em */
|
||||
$em = $container->get(EntityManagerInterface::class);
|
||||
$this->em = $em;
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
// Liberation explicite des handles pour eviter les fuites inter-tests
|
||||
// (pattern recommande par Symfony lorsque l'on capture le container).
|
||||
$this->em->clear();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testValidSitePassesValidation(): void
|
||||
{
|
||||
// Reutilise un nom deja present en fixtures (Chatellerault) impliquerait
|
||||
// une collision UniqueEntity. On prend donc un nom dedie aux tests.
|
||||
$site = new Site('Test-Valid-'.uniqid('', true), 'Poitiers', '86000', '#056CF2', 'Adresse valide');
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertCount(0, $violations, (string) $violations);
|
||||
}
|
||||
|
||||
#[DataProvider('invalidColorProvider')]
|
||||
public function testColorMustBeHexRrggbb(string $color): void
|
||||
{
|
||||
$site = new Site('Test-'.uniqid('', true), 'Y', '12345', $color, 'Addr');
|
||||
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertGreaterThan(0, $violations->count(), sprintf('La couleur "%s" devrait etre rejetee.', $color));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{string}>
|
||||
*/
|
||||
public static function invalidColorProvider(): iterable
|
||||
{
|
||||
yield 'nom CSS' => ['red'];
|
||||
|
||||
yield 'hex court' => ['#FFF'];
|
||||
|
||||
yield 'hex sans diese' => ['FFFFFF'];
|
||||
|
||||
yield 'rgb()' => ['rgb(255, 0, 0)'];
|
||||
|
||||
yield 'hex trop long' => ['#1234567'];
|
||||
|
||||
yield 'caractere non hex' => ['#12345G'];
|
||||
|
||||
yield 'vide' => [''];
|
||||
}
|
||||
|
||||
#[DataProvider('validColorProvider')]
|
||||
public function testValidColorsAreAccepted(string $color): void
|
||||
{
|
||||
$site = new Site('Test-'.uniqid('', true), 'Y', '12345', $color, 'Addr');
|
||||
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertCount(0, $violations, sprintf('La couleur "%s" devrait etre acceptee.', $color));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{string}>
|
||||
*/
|
||||
public static function validColorProvider(): iterable
|
||||
{
|
||||
yield 'majuscules' => ['#ABCDEF'];
|
||||
|
||||
yield 'minuscules' => ['#abcdef'];
|
||||
|
||||
yield 'mixte' => ['#0a1B2c'];
|
||||
|
||||
yield 'noir' => ['#000000'];
|
||||
|
||||
yield 'blanc' => ['#FFFFFF'];
|
||||
}
|
||||
|
||||
#[DataProvider('invalidPostalCodeProvider')]
|
||||
public function testPostalCodeMustMatchFrFormat(string $postalCode): void
|
||||
{
|
||||
$site = new Site('Test-'.uniqid('', true), 'Y', $postalCode, '#000000', 'Addr');
|
||||
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertGreaterThan(0, $violations->count(), sprintf('Le CP "%s" devrait etre rejete.', $postalCode));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{string}>
|
||||
*/
|
||||
public static function invalidPostalCodeProvider(): iterable
|
||||
{
|
||||
yield 'trop court' => ['1234'];
|
||||
|
||||
yield 'trop long' => ['123456'];
|
||||
|
||||
yield 'alphanumerique' => ['8610A'];
|
||||
|
||||
yield 'avec tiret' => ['86-100'];
|
||||
|
||||
yield 'vide' => [''];
|
||||
|
||||
yield 'avec espace' => ['86 100'];
|
||||
}
|
||||
|
||||
#[DataProvider('validPostalCodeProvider')]
|
||||
public function testValidPostalCodesAreAccepted(string $postalCode): void
|
||||
{
|
||||
$site = new Site('Test-'.uniqid('', true), 'Y', $postalCode, '#000000', 'Addr');
|
||||
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertCount(0, $violations, (string) $violations);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{string}>
|
||||
*/
|
||||
public static function validPostalCodeProvider(): iterable
|
||||
{
|
||||
yield 'metropole' => ['86100'];
|
||||
|
||||
yield 'paris' => ['75001'];
|
||||
|
||||
yield 'dom' => ['97100'];
|
||||
|
||||
yield 'corse' => ['20000'];
|
||||
}
|
||||
|
||||
public function testBlankNameIsRejected(): void
|
||||
{
|
||||
$site = new Site('', 'Y', '12345', '#000000', 'Addr');
|
||||
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertGreaterThan(0, $violations->count());
|
||||
}
|
||||
|
||||
public function testBlankCityIsRejected(): void
|
||||
{
|
||||
$site = new Site('Test-'.uniqid('', true), '', '12345', '#000000', 'Addr');
|
||||
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertGreaterThan(0, $violations->count());
|
||||
}
|
||||
|
||||
public function testBlankFullAddressIsRejected(): void
|
||||
{
|
||||
$site = new Site('Test-'.uniqid('', true), 'Y', '12345', '#000000', '');
|
||||
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertGreaterThan(0, $violations->count());
|
||||
}
|
||||
|
||||
public function testNameLongerThan100CharsIsRejected(): void
|
||||
{
|
||||
$site = new Site(str_repeat('a', 101), 'Y', '12345', '#000000', 'Addr');
|
||||
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertGreaterThan(0, $violations->count());
|
||||
}
|
||||
|
||||
public function testCityLongerThan100CharsIsRejected(): void
|
||||
{
|
||||
$site = new Site('Test-'.uniqid('', true), str_repeat('a', 101), '12345', '#000000', 'Addr');
|
||||
|
||||
$violations = $this->validator->validate($site);
|
||||
|
||||
self::assertGreaterThan(0, $violations->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifie que la contrainte UniqueEntity(name) est effectivement appliquee
|
||||
* par le validator Symfony (via le validateur Doctrine sous-jacent).
|
||||
*
|
||||
* Le test est auto-suffisant : il persiste lui-meme un site porteur d'un
|
||||
* nom unique, puis tente de valider un second Site avec le meme nom. Le
|
||||
* site cree est supprime en fin de test pour ne pas laisser de trace
|
||||
* inter-tests (pattern transactionnel non utilise ici car un seul test
|
||||
* persiste, un cleanup explicite suffit).
|
||||
*/
|
||||
public function testDuplicateNameIsRejected(): void
|
||||
{
|
||||
// Nom unique par execution pour eviter toute collision avec les
|
||||
// fixtures (Chatellerault, Saint-Jean, Pommevic) ou des tests
|
||||
// paralleles.
|
||||
$name = 'Test-Duplicate-'.uniqid('', true);
|
||||
$original = new Site($name, 'Poitiers', '86000', '#056CF2', 'Adresse originale');
|
||||
$this->em->persist($original);
|
||||
$this->em->flush();
|
||||
|
||||
try {
|
||||
$duplicate = new Site($name, 'Autre ville', '75001', '#FF0000', 'Autre adresse');
|
||||
$violations = $this->validator->validate($duplicate);
|
||||
|
||||
self::assertGreaterThan(0, $violations->count(), 'Un site homonyme doit lever au moins une violation.');
|
||||
|
||||
// Assertion precise : on veut s'assurer que la violation levee
|
||||
// est bien UniqueEntity sur `name`, pas une autre contrainte
|
||||
// qui passerait par hasard (matching de message trop laxe).
|
||||
$found = false;
|
||||
foreach ($violations as $violation) {
|
||||
if (UniqueEntity::NOT_UNIQUE_ERROR === $violation->getCode()
|
||||
&& 'name' === $violation->getPropertyPath()) {
|
||||
$found = true;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
self::assertTrue($found, 'Violation UniqueEntity(name) attendue (code NOT_UNIQUE_ERROR sur property `name`).');
|
||||
} finally {
|
||||
$this->em->remove($original);
|
||||
$this->em->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user