MissionValidationService.php
1 <?php 2 3 namespace ButA2SaeS3\services; 4 5 use ButA2SaeS3\dto\AddMissionDto; 6 use ButA2SaeS3\dto\UpdateMissionDto; 7 use ButA2SaeS3\validation\ValidationResult; 8 9 class MissionValidationService 10 { 11 public static function validateAddMission(array $data): ValidationResult 12 { 13 return self::validateMission($data, null); 14 } 15 16 public static function validateUpdateMission(array $data, int $id): ValidationResult 17 { 18 return self::validateMission($data, $id); 19 } 20 21 private static function validateMission(array $data, ?int $id): ValidationResult 22 { 23 $result = ValidationResult::empty(); 24 25 $title = trim($data['title'] ?? ''); 26 $description = trim($data['description'] ?? ''); 27 $location = trim($data['location'] ?? ''); 28 $startDate = $data['start_date'] ?? ''; 29 $startTime = $data['start_time'] ?? ''; 30 $endDate = $data['end_date'] ?? ''; 31 $endTime = $data['end_time'] ?? ''; 32 $capacity = $data['capacity'] ?? null; 33 $budget = $data['budget_cents'] ?? null; 34 35 if ($title === '') { 36 $result->addMessage('title', 'Le titre est requis'); 37 } 38 if ($description === '') { 39 $result->addMessage('description', 'La description est requise'); 40 } 41 if ($location === '') { 42 $result->addMessage('location', 'Le lieu est requis'); 43 } 44 45 $start_at = strtotime($startDate . ' ' . $startTime); 46 $end_at = strtotime($endDate . ' ' . $endTime); 47 48 if ($start_at === false || $end_at === false) { 49 $result->addMessage('datetime', "Format de date/heure invalide"); 50 } elseif ($start_at >= $end_at) { 51 $result->addMessage('datetime', "La date de fin doit être après la date de début"); 52 } 53 54 if ($capacity !== null && $capacity !== '') { 55 if (!is_numeric($capacity) || $capacity <= 0) { 56 $result->addMessage('capacity', "La capacité doit être un nombre positif"); 57 } 58 } 59 60 if ($budget !== null && $budget !== '') { 61 if (!is_numeric($budget) || $budget < 0) { 62 $result->addMessage('budget_cents', "Le budget doit être un nombre positif ou nul"); 63 } 64 } 65 66 if ($result->hasMessages()) { 67 return $result; 68 } 69 70 $dtoBudget = $budget !== null && $budget !== '' ? (int)($budget * 100) : 0; 71 $dtoCapacity = ($capacity !== null && $capacity !== '') ? (int)$capacity : null; 72 73 if ($id === null) { 74 $dto = new AddMissionDto( 75 $title, 76 $description, 77 $location, 78 $start_at, 79 $end_at, 80 $dtoCapacity, 81 $dtoBudget 82 ); 83 } else { 84 $dto = new UpdateMissionDto( 85 $id, 86 $title, 87 $description, 88 $location, 89 $start_at, 90 $end_at, 91 $dtoCapacity, 92 $dtoBudget 93 ); 94 } 95 96 $result->setValue($dto); 97 return $result; 98 } 99 }