feat: Provisionner automatiquement un nouvel établissement
Some checks failed
CI / Backend Tests (push) Has been cancelled
CI / Frontend Tests (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
CI / Naming Conventions (push) Has been cancelled
CI / Build Check (push) Has been cancelled

Lorsqu'un super-admin crée un établissement via l'interface, le système
doit automatiquement créer la base tenant, exécuter les migrations,
créer le premier utilisateur admin et envoyer l'invitation — le tout
de manière asynchrone pour ne pas bloquer la réponse HTTP.

Ce mécanisme rend chaque établissement opérationnel dès sa création
sans intervention manuelle sur l'infrastructure.
This commit is contained in:
2026-04-08 13:55:41 +02:00
parent bec211ebf0
commit dc2be898d5
171 changed files with 11703 additions and 700 deletions

View File

@@ -0,0 +1,271 @@
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Scolarite\Infrastructure\Api\Controller;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Application\Command\UploadHomeworkAttachment\UploadHomeworkAttachmentHandler;
use App\Scolarite\Application\Port\FileStorage;
use App\Scolarite\Domain\Model\Homework\Homework;
use App\Scolarite\Domain\Model\Homework\HomeworkAttachment;
use App\Scolarite\Domain\Model\Homework\HomeworkAttachmentId;
use App\Scolarite\Domain\Repository\HomeworkRepository;
use App\Scolarite\Infrastructure\Api\Controller\HomeworkAttachmentController;
use App\Scolarite\Infrastructure\Persistence\InMemory\InMemoryHomeworkAttachmentRepository;
use App\Scolarite\Infrastructure\Persistence\InMemory\InMemoryHomeworkRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use App\Tests\Unit\Scolarite\Infrastructure\Storage\InMemoryFileStorage;
use DateTimeImmutable;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
final class HomeworkAttachmentControllerTest extends TestCase
{
private const string TENANT_ID = '550e8400-e29b-41d4-a716-446655440001';
private const string TEACHER_ID = '550e8400-e29b-41d4-a716-446655440010';
private const string OTHER_TEACHER_ID = '550e8400-e29b-41d4-a716-446655440099';
private InMemoryHomeworkRepository $homeworkRepository;
private InMemoryHomeworkAttachmentRepository $attachmentRepository;
private InMemoryFileStorage $fileStorage;
protected function setUp(): void
{
$this->homeworkRepository = new InMemoryHomeworkRepository();
$this->attachmentRepository = new InMemoryHomeworkAttachmentRepository();
$this->fileStorage = new InMemoryFileStorage();
}
#[Test]
public function downloadReturnsStreamedResponseForExistingAttachment(): void
{
$homework = $this->createHomework();
$this->homeworkRepository->save($homework);
$attachment = $this->createAttachment('exercices.pdf', 'homework/files/exercices.pdf');
$this->attachmentRepository->save($homework->id, $attachment);
$this->fileStorage->upload('homework/files/exercices.pdf', 'PDF content here', 'application/pdf');
$controller = $this->createController(self::TEACHER_ID);
$response = $controller->download((string) $homework->id, (string) $attachment->id);
self::assertInstanceOf(StreamedResponse::class, $response);
self::assertSame(200, $response->getStatusCode());
self::assertSame('application/pdf', $response->headers->get('Content-Type'));
self::assertStringContainsString('exercices.pdf', $response->headers->get('Content-Disposition') ?? '');
}
#[Test]
public function downloadReturns404ForNonExistentAttachment(): void
{
$homework = $this->createHomework();
$this->homeworkRepository->save($homework);
$controller = $this->createController(self::TEACHER_ID);
$this->expectException(NotFoundHttpException::class);
$controller->download((string) $homework->id, 'non-existent-attachment-id');
}
#[Test]
public function downloadReturns404WhenFileNotFoundInStorage(): void
{
$homework = $this->createHomework();
$this->homeworkRepository->save($homework);
$attachment = $this->createAttachment('missing.pdf', 'homework/files/missing.pdf');
$this->attachmentRepository->save($homework->id, $attachment);
// File NOT uploaded to storage — simulates a missing blob
$controller = $this->createController(self::TEACHER_ID);
$this->expectException(NotFoundHttpException::class);
$controller->download((string) $homework->id, (string) $attachment->id);
}
#[Test]
public function downloadDeniesAccessToNonOwnerTeacher(): void
{
$homework = $this->createHomework();
$this->homeworkRepository->save($homework);
$attachment = $this->createAttachment('exercices.pdf', 'homework/files/exercices.pdf');
$this->attachmentRepository->save($homework->id, $attachment);
$controller = $this->createController(self::OTHER_TEACHER_ID);
$this->expectException(AccessDeniedHttpException::class);
$controller->download((string) $homework->id, (string) $attachment->id);
}
#[Test]
public function listDeniesAccessToNonOwnerTeacher(): void
{
$homework = $this->createHomework();
$this->homeworkRepository->save($homework);
$controller = $this->createController(self::OTHER_TEACHER_ID);
$this->expectException(AccessDeniedHttpException::class);
$controller->list((string) $homework->id);
}
#[Test]
public function deleteDeniesAccessToNonOwnerTeacher(): void
{
$homework = $this->createHomework();
$this->homeworkRepository->save($homework);
$attachment = $this->createAttachment('exercices.pdf', 'homework/files/exercices.pdf');
$this->attachmentRepository->save($homework->id, $attachment);
$controller = $this->createController(self::OTHER_TEACHER_ID);
$this->expectException(AccessDeniedHttpException::class);
$controller->delete((string) $homework->id, (string) $attachment->id);
}
#[Test]
public function downloadDeniesAccessToUnauthenticatedUser(): void
{
$homework = $this->createHomework();
$this->homeworkRepository->save($homework);
$controller = $this->createControllerWithoutUser();
$this->expectException(AccessDeniedHttpException::class);
$controller->download((string) $homework->id, 'any-attachment-id');
}
#[Test]
public function listReturnsAttachmentsForOwner(): void
{
$homework = $this->createHomework();
$this->homeworkRepository->save($homework);
$attachment = $this->createAttachment('exercices.pdf', 'homework/files/exercices.pdf');
$this->attachmentRepository->save($homework->id, $attachment);
$controller = $this->createController(self::TEACHER_ID);
$response = $controller->list((string) $homework->id);
self::assertSame(200, $response->getStatusCode());
/** @var array<array{id: string, filename: string}> $data */
$data = json_decode((string) $response->getContent(), true);
self::assertCount(1, $data);
self::assertSame('exercices.pdf', $data[0]['filename']);
}
#[Test]
public function deleteRemovesAttachmentAndFile(): void
{
$homework = $this->createHomework();
$this->homeworkRepository->save($homework);
$attachment = $this->createAttachment('exercices.pdf', 'homework/files/exercices.pdf');
$this->attachmentRepository->save($homework->id, $attachment);
$this->fileStorage->upload('homework/files/exercices.pdf', 'content', 'application/pdf');
$controller = $this->createController(self::TEACHER_ID);
$response = $controller->delete((string) $homework->id, (string) $attachment->id);
self::assertSame(204, $response->getStatusCode());
self::assertEmpty($this->attachmentRepository->findByHomeworkId($homework->id));
self::assertFalse($this->fileStorage->has('homework/files/exercices.pdf'));
}
private function createHomework(): Homework
{
return Homework::creer(
tenantId: TenantId::fromString(self::TENANT_ID),
classId: ClassId::fromString('550e8400-e29b-41d4-a716-446655440020'),
subjectId: SubjectId::fromString('550e8400-e29b-41d4-a716-446655440030'),
teacherId: UserId::fromString(self::TEACHER_ID),
title: 'Devoir test',
description: 'Description',
dueDate: new DateTimeImmutable('2026-05-01'),
now: new DateTimeImmutable('2026-04-09'),
);
}
private function createAttachment(string $filename, string $filePath): HomeworkAttachment
{
return new HomeworkAttachment(
id: HomeworkAttachmentId::generate(),
filename: $filename,
filePath: $filePath,
fileSize: 5000,
mimeType: 'application/pdf',
uploadedAt: new DateTimeImmutable('2026-04-09'),
);
}
private function createController(string $teacherId): HomeworkAttachmentController
{
$securityUser = new SecurityUser(
userId: UserId::fromString($teacherId),
email: 'teacher@example.com',
hashedPassword: 'hashed',
tenantId: TenantId::fromString(self::TENANT_ID),
roles: ['ROLE_PROF'],
);
$security = $this->createMock(Security::class);
$security->method('getUser')->willReturn($securityUser);
$uploadHandler = $this->createUploadHandler($this->homeworkRepository, $this->fileStorage);
return new HomeworkAttachmentController(
security: $security,
homeworkRepository: $this->homeworkRepository,
attachmentRepository: $this->attachmentRepository,
uploadHandler: $uploadHandler,
fileStorage: $this->fileStorage,
);
}
private function createControllerWithoutUser(): HomeworkAttachmentController
{
$security = $this->createMock(Security::class);
$security->method('getUser')->willReturn(null);
$uploadHandler = $this->createUploadHandler($this->homeworkRepository, $this->fileStorage);
return new HomeworkAttachmentController(
security: $security,
homeworkRepository: $this->homeworkRepository,
attachmentRepository: $this->attachmentRepository,
uploadHandler: $uploadHandler,
fileStorage: $this->fileStorage,
);
}
private function createUploadHandler(HomeworkRepository $homeworkRepository, FileStorage $fileStorage): UploadHomeworkAttachmentHandler
{
$clock = new class implements Clock {
public function now(): DateTimeImmutable
{
return new DateTimeImmutable('2026-04-09 10:00:00');
}
};
return new UploadHomeworkAttachmentHandler($homeworkRepository, $fileStorage, $clock);
}
}

View File

@@ -0,0 +1,459 @@
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Scolarite\Infrastructure\Security;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Application\Port\EnseignantAffectationChecker;
use App\Scolarite\Application\Service\AutorisationSaisieNotesChecker;
use App\Scolarite\Domain\Model\Evaluation\Coefficient;
use App\Scolarite\Domain\Model\Evaluation\Evaluation;
use App\Scolarite\Domain\Model\Evaluation\GradeScale;
use App\Scolarite\Domain\Model\TeacherReplacement\ClassSubjectPair;
use App\Scolarite\Domain\Model\TeacherReplacement\TeacherReplacement;
use App\Scolarite\Infrastructure\Persistence\InMemory\InMemoryTeacherReplacementRepository;
use App\Scolarite\Infrastructure\Security\GradeVoter;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use App\Shared\Infrastructure\Tenant\TenantConfig;
use App\Shared\Infrastructure\Tenant\TenantContext;
use App\Shared\Infrastructure\Tenant\TenantId as InfraTenantId;
use DateTimeImmutable;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
final class GradeVoterTest extends TestCase
{
private TenantId $tenantId;
private ClassId $classId;
private SubjectId $subjectId;
private InMemoryTeacherReplacementRepository $replacementRepository;
private TenantContext $tenantContext;
private DateTimeImmutable $now;
private GradeVoter $voter;
/** @var array<string, bool> */
private array $affectationResults = [];
protected function setUp(): void
{
$this->tenantId = TenantId::generate();
$this->classId = ClassId::generate();
$this->subjectId = SubjectId::generate();
$this->replacementRepository = new InMemoryTeacherReplacementRepository();
$this->tenantContext = new TenantContext();
$this->now = new DateTimeImmutable('2026-04-13 10:00:00');
$this->tenantContext->setCurrentTenant(new TenantConfig(
tenantId: InfraTenantId::fromString((string) $this->tenantId),
subdomain: 'test',
databaseUrl: 'sqlite:///:memory:',
));
$this->affectationResults = [];
$test = $this;
$affectationChecker = new class($test) implements EnseignantAffectationChecker {
public function __construct(private readonly GradeVoterTest $test)
{
}
public function estAffecte(
UserId $teacherId,
ClassId $classId,
SubjectId $subjectId,
TenantId $tenantId,
): bool {
return $this->test->getAffectationResult((string) $teacherId);
}
};
$autorisationChecker = new AutorisationSaisieNotesChecker(
$affectationChecker,
$this->replacementRepository,
);
$clock = $this->createMock(Clock::class);
$clock->method('now')->willReturn($this->now);
$this->voter = new GradeVoter(
$autorisationChecker,
$this->tenantContext,
$clock,
);
}
public function getAffectationResult(string $teacherId): bool
{
return $this->affectationResults[$teacherId] ?? false;
}
private function setTeacherAffecte(UserId $teacherId): void
{
$this->affectationResults[(string) $teacherId] = true;
}
#[Test]
public function itAbstainsForUnrelatedAttributes(): void
{
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value);
$result = $this->voter->vote($token, $evaluation, ['SOME_OTHER_ATTRIBUTE']);
self::assertSame(Voter::ACCESS_ABSTAIN, $result);
}
#[Test]
public function itAbstainsWhenSubjectIsNotAnEvaluation(): void
{
$token = $this->tokenWithSecurityUser(Role::PROF->value);
$result = $this->voter->vote($token, null, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_ABSTAIN, $result);
}
#[Test]
public function itDeniesAccessToUnauthenticatedUsers(): void
{
$evaluation = $this->createEvaluation();
$token = $this->createMock(TokenInterface::class);
$token->method('getUser')->willReturn(null);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_DENIED, $result);
}
#[Test]
public function itDeniesAccessToNonSecurityUser(): void
{
$evaluation = $this->createEvaluation();
$user = $this->createMock(UserInterface::class);
$user->method('getRoles')->willReturn([Role::PROF->value]);
$token = $this->createMock(TokenInterface::class);
$token->method('getUser')->willReturn($user);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_DENIED, $result);
}
#[Test]
public function itGrantsViewToAdmin(): void
{
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::ADMIN->value);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_GRANTED, $result);
}
#[Test]
public function itDeniesEditToAdmin(): void
{
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::ADMIN->value);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::EDIT]);
self::assertSame(Voter::ACCESS_DENIED, $result);
}
#[Test]
public function itGrantsViewToSuperAdmin(): void
{
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::SUPER_ADMIN->value);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_GRANTED, $result);
}
#[Test]
public function itGrantsViewToAssignedTeacher(): void
{
$teacherId = UserId::generate();
$this->setTeacherAffecte($teacherId);
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value, $teacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_GRANTED, $result);
}
#[Test]
public function itGrantsEditToAssignedTeacher(): void
{
$teacherId = UserId::generate();
$this->setTeacherAffecte($teacherId);
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value, $teacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::EDIT]);
self::assertSame(Voter::ACCESS_GRANTED, $result);
}
#[Test]
public function itDeniesEditToUnassignedTeacher(): void
{
$teacherId = UserId::generate();
// No assignment set
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value, $teacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::EDIT]);
self::assertSame(Voter::ACCESS_DENIED, $result);
}
#[Test]
public function itGrantsViewToEvaluationOwnerWithoutAssignment(): void
{
$teacherId = UserId::generate();
// Teacher owns the evaluation but is no longer assigned
$evaluation = $this->createEvaluation(teacherId: $teacherId);
$token = $this->tokenWithSecurityUser(Role::PROF->value, $teacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_GRANTED, $result);
}
#[Test]
public function itDeniesEditToEvaluationOwnerWithoutAssignment(): void
{
$teacherId = UserId::generate();
// Teacher owns the evaluation but is no longer assigned
$evaluation = $this->createEvaluation(teacherId: $teacherId);
$token = $this->tokenWithSecurityUser(Role::PROF->value, $teacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::EDIT]);
self::assertSame(Voter::ACCESS_DENIED, $result);
}
#[Test]
public function itGrantsViewToActiveReplacement(): void
{
$replacementTeacherId = UserId::generate();
$this->createActiveReplacement($replacementTeacherId);
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value, $replacementTeacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_GRANTED, $result);
}
#[Test]
public function itGrantsEditToActiveReplacement(): void
{
$replacementTeacherId = UserId::generate();
$this->createActiveReplacement($replacementTeacherId);
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value, $replacementTeacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::EDIT]);
self::assertSame(Voter::ACCESS_GRANTED, $result);
}
#[Test]
public function itDeniesEditToExpiredReplacement(): void
{
$replacementTeacherId = UserId::generate();
$this->createExpiredReplacement($replacementTeacherId);
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value, $replacementTeacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::EDIT]);
self::assertSame(Voter::ACCESS_DENIED, $result);
}
#[Test]
public function itDeniesViewToExpiredReplacementWhoIsNotOwner(): void
{
$replacementTeacherId = UserId::generate();
$this->createExpiredReplacement($replacementTeacherId);
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value, $replacementTeacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_DENIED, $result);
}
#[Test]
public function itDeniesViewToReplacementOnDifferentClassSubject(): void
{
$replacementTeacherId = UserId::generate();
// Remplacement actif mais sur une AUTRE classe/matière
$otherClassId = ClassId::generate();
$otherSubjectId = SubjectId::generate();
$replacement = TeacherReplacement::designer(
tenantId: $this->tenantId,
replacedTeacherId: UserId::generate(),
replacementTeacherId: $replacementTeacherId,
startDate: $this->now->modify('-1 day'),
endDate: $this->now->modify('+7 days'),
classes: [new ClassSubjectPair($otherClassId, $otherSubjectId)],
reason: 'Maladie',
createdBy: UserId::generate(),
now: $this->now->modify('-1 day'),
);
$this->replacementRepository->save($replacement);
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value, $replacementTeacherId);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_DENIED, $result);
}
#[Test]
public function itDeniesViewToNonTeacherNonAdminRoles(): void
{
$evaluation = $this->createEvaluation();
foreach ([Role::ELEVE->value, Role::PARENT->value, Role::SECRETARIAT->value, Role::VIE_SCOLAIRE->value] as $role) {
$token = $this->tokenWithSecurityUser($role);
$result = $this->voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_DENIED, $result, "Role {$role} should be denied VIEW");
}
}
#[Test]
public function itDeniesWhenNoTenantIsSet(): void
{
$teacherId = UserId::generate();
$this->setTeacherAffecte($teacherId);
$tenantContext = new TenantContext();
$clock = $this->createMock(Clock::class);
$clock->method('now')->willReturn($this->now);
$test = $this;
$affectationChecker = new class($test) implements EnseignantAffectationChecker {
public function __construct(private readonly GradeVoterTest $test)
{
}
public function estAffecte(
UserId $teacherId,
ClassId $classId,
SubjectId $subjectId,
TenantId $tenantId,
): bool {
return $this->test->getAffectationResult((string) $teacherId);
}
};
$autorisationChecker = new AutorisationSaisieNotesChecker(
$affectationChecker,
$this->replacementRepository,
);
$voter = new GradeVoter(
$autorisationChecker,
$tenantContext,
$clock,
);
$evaluation = $this->createEvaluation();
$token = $this->tokenWithSecurityUser(Role::PROF->value, $teacherId);
$result = $voter->vote($token, $evaluation, [GradeVoter::VIEW]);
self::assertSame(Voter::ACCESS_DENIED, $result);
}
private function createEvaluation(?UserId $teacherId = null): Evaluation
{
return Evaluation::creer(
tenantId: $this->tenantId,
classId: $this->classId,
subjectId: $this->subjectId,
teacherId: $teacherId ?? UserId::generate(),
title: 'Contrôle de maths',
description: null,
evaluationDate: $this->now,
gradeScale: new GradeScale(20),
coefficient: new Coefficient(1.0),
now: $this->now,
);
}
private function createActiveReplacement(UserId $replacementTeacherId): void
{
$replacement = TeacherReplacement::designer(
tenantId: $this->tenantId,
replacedTeacherId: UserId::generate(),
replacementTeacherId: $replacementTeacherId,
startDate: $this->now->modify('-1 day'),
endDate: $this->now->modify('+7 days'),
classes: [new ClassSubjectPair($this->classId, $this->subjectId)],
reason: 'Maladie',
createdBy: UserId::generate(),
now: $this->now->modify('-1 day'),
);
$this->replacementRepository->save($replacement);
}
private function createExpiredReplacement(UserId $replacementTeacherId): void
{
$replacement = TeacherReplacement::designer(
tenantId: $this->tenantId,
replacedTeacherId: UserId::generate(),
replacementTeacherId: $replacementTeacherId,
startDate: $this->now->modify('-14 days'),
endDate: $this->now->modify('-1 day'),
classes: [new ClassSubjectPair($this->classId, $this->subjectId)],
reason: 'Maladie',
createdBy: UserId::generate(),
now: $this->now->modify('-14 days'),
);
$this->replacementRepository->save($replacement);
}
private function tokenWithSecurityUser(string $role, ?UserId $userId = null): TokenInterface
{
$securityUser = new SecurityUser(
userId: $userId ?? UserId::generate(),
email: 'test@example.com',
hashedPassword: 'hashed',
tenantId: $this->tenantId,
roles: [$role],
);
$token = $this->createMock(TokenInterface::class);
$token->method('getUser')->willReturn($securityUser);
return $token;
}
}

View File

@@ -6,10 +6,16 @@ namespace App\Tests\Unit\Scolarite\Infrastructure\Storage;
use App\Scolarite\Application\Port\FileStorage;
use function fopen;
use function fwrite;
use function is_string;
use Override;
use function rewind;
use RuntimeException;
final class InMemoryFileStorage implements FileStorage
{
/** @var array<string, string> */
@@ -29,6 +35,21 @@ final class InMemoryFileStorage implements FileStorage
unset($this->files[$path]);
}
#[Override]
public function readStream(string $path): mixed
{
if (!isset($this->files[$path])) {
throw new RuntimeException("File not found: {$path}");
}
/** @var resource $stream */
$stream = fopen('php://memory', 'r+');
fwrite($stream, $this->files[$path]);
rewind($stream);
return $stream;
}
public function has(string $path): bool
{
return isset($this->files[$path]);

View File

@@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Scolarite\Infrastructure\Storage;
use App\Scolarite\Infrastructure\Storage\S3FileStorage;
use function fopen;
use League\Flysystem\Filesystem;
use League\Flysystem\UnableToDeleteFile;
use League\Flysystem\UnableToReadFile;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use ReflectionClass;
use RuntimeException;
final class S3FileStorageTest extends TestCase
{
private Filesystem $filesystem;
private LoggerInterface $logger;
private S3FileStorage $storage;
protected function setUp(): void
{
$this->filesystem = $this->createMock(Filesystem::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->storage = $this->createStorageWithMockedFilesystem($this->filesystem, $this->logger);
}
#[Test]
public function uploadWritesStringContentToFilesystem(): void
{
$this->filesystem->expects(self::once())
->method('write')
->with('homework/abc/file.pdf', 'fake content', ['ContentType' => 'application/pdf']);
$result = $this->storage->upload('homework/abc/file.pdf', 'fake content', 'application/pdf');
self::assertSame('homework/abc/file.pdf', $result);
}
#[Test]
public function uploadWritesStreamContentToFilesystem(): void
{
/** @var resource $stream */
$stream = fopen('php://memory', 'r+');
$this->filesystem->expects(self::once())
->method('writeStream')
->with('homework/abc/file.pdf', $stream, ['ContentType' => 'application/pdf']);
$result = $this->storage->upload('homework/abc/file.pdf', $stream, 'application/pdf');
self::assertSame('homework/abc/file.pdf', $result);
}
#[Test]
public function deleteRemovesFileFromFilesystem(): void
{
$this->filesystem->expects(self::once())
->method('delete')
->with('homework/abc/file.pdf');
$this->logger->expects(self::never())
->method('warning');
$this->storage->delete('homework/abc/file.pdf');
}
#[Test]
public function deleteLogsWarningOnFailure(): void
{
$this->filesystem->expects(self::once())
->method('delete')
->willThrowException(UnableToDeleteFile::atLocation('homework/abc/file.pdf'));
$this->logger->expects(self::once())
->method('warning')
->with(
'S3 delete failed, possible orphan blob: {path}',
self::callback(static fn (array $context): bool => $context['path'] === 'homework/abc/file.pdf'),
);
$this->storage->delete('homework/abc/file.pdf');
}
#[Test]
public function readStreamReturnsResourceFromFilesystem(): void
{
/** @var resource $expectedStream */
$expectedStream = fopen('php://memory', 'r+');
$this->filesystem->expects(self::once())
->method('readStream')
->with('homework/abc/file.pdf')
->willReturn($expectedStream);
$result = $this->storage->readStream('homework/abc/file.pdf');
self::assertSame($expectedStream, $result);
}
#[Test]
public function readStreamThrowsRuntimeExceptionOnMissingFile(): void
{
$this->filesystem->expects(self::once())
->method('readStream')
->with('homework/abc/missing.pdf')
->willThrowException(UnableToReadFile::fromLocation('homework/abc/missing.pdf'));
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Impossible de lire le fichier : homework/abc/missing.pdf');
$this->storage->readStream('homework/abc/missing.pdf');
}
/**
* Creates an S3FileStorage instance with a mocked Filesystem injected via reflection.
*
* S3FileStorage is `final readonly` and its constructor creates a real S3Client,
* so we bypass it with newInstanceWithoutConstructor() and inject mocks directly.
* If the class gains new properties, this method must be updated.
*/
private function createStorageWithMockedFilesystem(Filesystem $filesystem, LoggerInterface $logger): S3FileStorage
{
$reflection = new ReflectionClass(S3FileStorage::class);
$storage = $reflection->newInstanceWithoutConstructor();
$fsProp = $reflection->getProperty('filesystem');
$fsProp->setValue($storage, $filesystem);
$loggerProp = $reflection->getProperty('logger');
$loggerProp->setValue($storage, $logger);
return $storage;
}
}