welcome back to dyb-tech

This commit is contained in:
Daniel Guzman
2024-05-18 02:28:01 +02:00
parent 9513cdba09
commit 9f30bc98c7
6149 changed files with 668407 additions and 0 deletions
View File
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace DMD\LaLigaApi\Controller;
use DMD\LaLigaApi\Service\League\acceptJoinLeagueRequest\HandleAcceptJoinLeagueRequest;
use DMD\LaLigaApi\Service\League\createLeague\HandleCreateLeague;
use DMD\LaLigaApi\Service\League\declineJoinLeagueRequest\HandleDeclineJoinLeagueRequest;
use DMD\LaLigaApi\Service\League\getAllLeagues\HandleGetAllLeagues;
use DMD\LaLigaApi\Service\League\getLeagueById\HandleGetLeagueById;
use DMD\LaLigaApi\Service\League\newJoinLeagueRequest\HandleNewJoinLeagueRequest;
use DMD\LaLigaApi\Service\League\joinTeam\HandleCaptainRequest;
use DMD\LaLigaApi\Service\League\updateLeague\HandleUpdateLeague;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Routing\Annotation\Route;
class LeagueController extends AbstractController
{
#[Route('/api/league/new', name: 'app_league', methods: ['POST'])]
public function createLeague(Request $request, HandleCreateLeague $handleCreateLeague): JsonResponse
{
return $handleCreateLeague($request);
}
#[Route('/api/league/{$leagueId}', name: 'app_update_league', methods: ['PUT'])]
public function updateLeague(Request $request, HandleUpdateLeague $handleUpdateLeague, int $leagueId): JsonResponse
{
return $handleUpdateLeague($request, $leagueId);
}
#[Route('/api/league/{leagueId}/join', name: 'app_join_league', methods: ['PUT'])]
public function joinLeague(Request $request, HandleNewJoinLeagueRequest $handleJoinLeague, int $leagueId): JsonResponse
{
return $handleJoinLeague($request, $leagueId);
}
/**
* @throws TransportExceptionInterface
*/
#[Route('/api/league/{leagueId}/team/{teamId}', name: 'app_join_team', methods: ['PUT'])]
public function joinTeam(Request $request, HandleCaptainRequest $handleCaptainRequest, int $leagueId, int $teamId): JsonResponse
{
return $handleCaptainRequest($request, $leagueId, $teamId);
}
#[Route('/api/league/{leagueId}', name: 'app_get_league', methods: ['GET'])]
public function getLeagueById(Request $request, HandleGetLeagueById $handleGetLeagueById, int $leagueId): JsonResponse
{
return $handleGetLeagueById($request, $leagueId);
}
#[Route('/api/public/league', name: 'app_get_all_leagues', methods: ['GET'])]
public function getAllLeagues(HandleGetAllLeagues $handleGetAllLeagues): JsonResponse
{
return $handleGetAllLeagues();
}
/**
* @throws TransportExceptionInterface
*/
#[Route('api/league/{leagueId}/user/{userId}/accept', name: 'app_accept_join_request', methods: ['GET'])]
public function acceptJoinRequest(
Request $request,
HandleAcceptJoinLeagueRequest $handleAcceptJoinLeagueRequest,
int $leagueId,
int $userId
): JsonResponse
{
return $handleAcceptJoinLeagueRequest($request, $leagueId, $userId);
}
#[Route('api/league/{leagueId}/decline/{captainId}', name: 'app_decline_join_request', methods: ['GET'])]
public function declineJoinRequest(Request $request, HandleDeclineJoinLeagueRequest $handleDeclineJoinRequest, int $leagueId, int $captainId): JsonResponse
{
return $handleDeclineJoinRequest($request, $leagueId, $captainId);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace DMD\LaLigaApi\Controller;
use DMD\LaLigaApi\Service\User\Handlers\getNotifications\HandleGetNotifications;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class NotificationController extends AbstractController
{
#[Route('/api/notifications', name: 'app_get_notifications')]
public function getAllNotifications(HandleGetNotifications $handleGetNotifications): Response
{
return $handleGetNotifications();
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace DMD\LaLigaApi\Controller;
use DMD\LaLigaApi\Service\Season\addTeam\HandleAddTeam;
use DMD\LaLigaApi\Service\Season\createGameCalendar\HandleCreateGameCalendarRequest;
use DMD\LaLigaApi\Service\Season\createSeason\HandleCreateSeason;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class SeasonController extends AbstractController
{
#[Route('/api/league/{leagueId}/season/create', name: 'app_add_season', methods: ['POST'])]
public function addSeason(Request $request, HandleCreateSeason $handleCreateSeason, int $leagueId): JsonResponse
{
return $handleCreateSeason($request, $leagueId);
}
#[Route('/api/league/{leagueId}/season/{seasonId}/team', name: 'app_add_team', methods: ['POST'])]
public function addTeam(Request $request, HandleAddTeam $handleAddTeam, int $leagueId, int $seasonId): JsonResponse
{
return $handleAddTeam($request, $leagueId, $seasonId);
}
#[Route('/api/league/{leagueId}/season/{seasonId}/calendar', name: 'app_create_calendar', methods: ['POST'])]
public function createCalendar(Request $request, HandleCreateGameCalendarRequest $handleCreateGameCalendarRequest, int $leagueId, int $seasonId): JsonResponse
{
return $handleCreateGameCalendarRequest($request, $leagueId, $seasonId);
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace DMD\LaLigaApi\Controller;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\User\Handlers\delete\HandleDeleteUser;
use DMD\LaLigaApi\Service\User\Handlers\update\HandleUpdateUser;
use DMD\LaLigaApi\Service\User\Handlers\register\HandleRegistration;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
class UserController extends AbstractController
{
#[Route('/api/register', name: 'app_user_register', methods: ['POST'])]
public function createUser(Request $request, HandleRegistration $handleRegistration): JsonResponse
{
return $handleRegistration($request);
}
#[Route('/api/user/', name: 'app_user_delete', methods: ['DELETE'])]
public function deleteUser(Request $request, HandleDeleteUser $handleDeleteUser): JsonResponse
{
return $handleDeleteUser($request);
}
#[Route('/api/user/edit', name: 'app_update_user', methods: ['PUT'])]
public function updateUser(Request $request, HandleUpdateUser $handleUpdateUser): JsonResponse
{
return $handleUpdateUser($request);
}
#[Route('/api/user/password', name: 'app_user_change_password', methods: ['PUT'])]
public function changePassword(
Request $request,
UserRepository $userRepository,
UserPasswordHasherInterface $passwordHasher,
EntityManagerInterface $entityManager
): JsonResponse
{
$user = $userRepository->findOneBy([
'email' => ($request->toArray())['username']
]);
if (is_null($user))
{
throw new HttpException(
Response::HTTP_NOT_FOUND,
'User not found.'
);
}
$hashedPassword = $passwordHasher->hashPassword($user, ($request->toArray())['newPassword']);
$user->setPassword($hashedPassword);
$entityManager->persist($user);
$entityManager->flush($user);
$entityManager->clear();
return new JsonResponse([
'success' => true
]);
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Entity\CustomRole;
class CustomRoleDto
{
public int $id;
public string $name;
public \DateTimeImmutable $createdAt;
public int $userId;
public function toArray(): array
{
return [
'id' => $this->id ?? '',
'name' => $this->name ?? '',
'userId' => $this->userId ?? '',
'createdAt' => $this->createdAt ? $this->createdAt->format('Y-m-d H:i:s') : ''
];
}
public function fillFromArray(array $dataList): void
{
if (isset($dataList['id']))
{
$this->id = $dataList['id'];
}
if (!empty($dataList['name']))
{
$this->name = $dataList['name'];
}
if (!empty($dataList['createdAt']))
{
$this->createdAt = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dataList['createdAt']);
}
}
public function fillFromObject(CustomRole $customRole): void
{
if (!is_null($customRole->getId()))
{
$this->id = $customRole->getId();
}
if (!is_null($customRole->getName()))
{
$this->name = $customRole->getName();
}
if (!is_null($customRole->getCreatedAt()))
{
$this->name = $customRole->getCreatedAt();
}
if (!is_null(($customRole->getUser())->getId()))
{
$this->userId = ($customRole->getUser())->getId();
}
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Entity\Facility;
use phpDocumentor\Reflection\Types\Integer;
class FacilityDto
{
public int $id;
public string $name;
public string $address;
public bool $active;
public array $gameDtoList;
public array $seasonDtoList;
public \DateTime $createdAt;
public function toArray(): array
{
$seasonList = [];
if (!empty($this->seasonDtoList))
{
foreach ($this->seasonDtoList as $seasonDto)
{
$seasonList = $seasonDto->toArray();
}
}
return [
'id' => $this->id ?? '',
'name' => $this->name ?? '',
'address' => $this->address ?? '',
'seasonList' => $seasonList,
'createdAt' => !empty($this->createdAt) ? $this->createdAt->format('Y-m-d H:i:s') : ''
];
}
public function fillFromArray(array $dataList): void
{
if (isset($dataList['id']))
{
$this->id = $dataList['id'];
}
if (!empty($dataList['name']))
{
$this->name = $dataList['name'];
}
if (!empty($dataList['address']))
{
$this->address = $dataList['address'];
}
if (isset($dataList['active']))
{
$this->active = $dataList['active'];
}
if (!empty($dataList['seasonList']))
{
foreach ($dataList['seasonList'] as $seasonItem)
{
$seasonDto = new SeasonDto();
$seasonDto->fillFromArray($seasonItem);
$this->seasonDtoList[] = $seasonDto;
}
}
if (!empty($dataList['createdAt']))
{
$this->createdAt = \DateTime::createFromFormat('Y-m-d H:i:s', $dataList['createdAt'], new \DateTimeZone('Europe/Madrid'));
}
}
public function fillFromObject(Facility $facilityEntity): void
{
if ($facilityEntity->getId() !== null)
{
$this->id = $facilityEntity->getId();
}
if ($facilityEntity->getName() !== null)
{
$this->name = $facilityEntity->getName();
}
if ($facilityEntity->getAddress() !== null)
{
$this->address = $facilityEntity->getAddress();
}
if ($facilityEntity->getCreatedAt() !== null)
{
$this->createdAt = new \DateTime($facilityEntity->getCreatedAt(), new \DateTimeZone('Europe/Madrid'));
}
}
public function validate(): void
{
// if (empty($this->name))
// {
// $this->validationErrors[] = 'El nombre del equipo no puede estar vacío.';
// }
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Entity\File;
class FileDto
{
public int $id;
public string $name;
public string $type;
public \DateTime $createdAt;
public GameDto $gameDto;
public PlayerDto $playerDto;
public SeasonDto $seasonDto;
public function fillFromArray(array $dataList): void
{
if (isset($dataList['id']))
{
$this->id = $dataList['id'];
}
if (!empty($dataList['name']))
{
$this->name = $dataList['name'];
}
if (!empty($dataList['type']))
{
$this->type = $dataList['type'];
}
if (!empty($dataList['createdAt']))
{
$this->createdAt = \DateTime::createFromFormat('Y-m-d H:i:s', $dataList['createdAt']);
}
}
public function fillFromObject(File $fileEntity): void
{
if ($fileEntity->getId() !== null)
{
$this->id = $fileEntity->getId();
}
if ($fileEntity->getName() !== null)
{
$this->name = $fileEntity->getName();
}
if ($fileEntity->getPlayer() !== null)
{
$playerDto = new PlayerDto();
$playerDto->fillFromObject($fileEntity->getPlayer());
$this->playerDto = $playerDto;
}
if ($fileEntity->getSeason() !== null)
{
$seasonDto = new SeasonDto();
$seasonDto->fillFromObject($fileEntity->getSeason());
$this->seasonDto = $seasonDto;
}
if ($fileEntity->getGame() !== null)
{
$gameDto = new GameDto();
$gameDto->fillFromObject($fileEntity->getGame());
$this->gameDto = $gameDto;
}
}
public function validate(): void
{
}
}
+194
View File
@@ -0,0 +1,194 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Entity\Game;
class GameDto
{
public int $id;
public TeamDto $homeTeamDto;
public TeamDto $awayTeamDto;
public \DateTime $plannedDate;
public \DateTime $gameDateTime;
public string $notes;
public array $fileDtoList;
public SeasonDto $seasonDto;
public FacilityDto $facilityDto;
public int $pointsHome;
public int $pointsAway;
public \DateTimeImmutable $createdAt;
public \DateTimeImmutable $updatedAt;
public array $validationErrors;
public function toArray(): array
{
$cleanResponseArray = [];
$responseArray = [
'id' => $this->id ?? null,
'homeTeam' => $this->homeTeamDto->toArray() ?? [],
'awayTeam' => $this->awayTeamDto->toArray() ?? [],
'plannedDate' => !empty($this->plannedDate) ? $this->plannedDate->format('Y-m-d H:i:s') : null,
'gameDateTime' => !empty($this->gameDateTime) ? $this->gameDateTime->format('Y-m-d H:i:s') : null,
'season' => $this->seasonDto->toArray() ?? [],
'notes' => $this->notes ?? null,
'facility' => $this->facilityDto->toArray() ?? [],
'pointsHome' => $this->pointsHome ?? 0,
'pointsAway' => $this->pointsAway ?? 0,
'createdAt' => !empty($this->createdAt) ? $this->createdAt->format('Y-m-d H:i:s') : null,
'updatedAt' => !empty($this->updatedAt) ? $this->updatedAt->format('Y-m-d H:i:s') : null
];
foreach ($responseArray as $key => $value)
{
if ($value !== null)
{
$cleanResponseArray[$key] = $value;
}
}
return $cleanResponseArray;
}
public function fillFromArray(array $dataList): void
{
if (!empty($dataList['id']))
{
$this->id = $dataList['id'];
}
if (!empty($dataList['plannedDate']))
{
$this->plannedDate = new \DateTime($dataList['plannedDate']);
}
if (!empty($dataList['gameDateTime']))
{
$this->gameDateTime = new \DateTime($dataList['gameDateTime']);
}
if (!empty($dataList['notes']))
{
$this->notes = $dataList['notes'];
}
if (!empty($dataList['pointsHome']))
{
$this->pointsHome = $dataList['pointsHome'];
}
if (!empty($dataList['pointsAway']))
{
$this->pointsAway = $dataList['pointsAway'];
}
if (!empty($dataList['createdAt']))
{
$this->createdAt = new \DateTimeImmutable($dataList['createdAt'], new \DateTimeZone('Europe/Madrid'));
}
if (!empty($dataList['updatedAt']))
{
$this->updatedAt = new \DateTimeImmutable($dataList['updatedAt'], new \DateTimeZone('Europe/Madrid'));
}
}
public function fillFromObject(Game $gameEntity): void
{
if ($gameEntity->getId() !== null)
{
$this->id = $gameEntity->getId();
}
if ($gameEntity->getSeason() !== null)
{
$seasonDto = new SeasonDto();
$seasonDto->fillFromObject($gameEntity->getSeason());
$this->seasonDto = $seasonDto;
}
if ($gameEntity->getFacility() !== null)
{
$facilityDto = new FacilityDto();
$facilityDto->fillFromObject($gameEntity->getFacility());
$this->facilityDto = $facilityDto;
}
if ($gameEntity->getHomeTeam() !== null)
{
$teamDto = new TeamDto();
$teamDto->fillFromObject($gameEntity->getHomeTeam());
$this->homeTeamDto = $teamDto;
}
if ($gameEntity->getAwayTeam() !== null)
{
$teamDto = new TeamDto();
$teamDto->fillFromObject($gameEntity->getAwayTeam());
$this->awayTeamDto = $teamDto;
}
if ($gameEntity->getFiles() !== null)
{
$fileIterator = $gameEntity->getFiles()->getIterator();
foreach ($fileIterator as $fileEntity)
{
$fileDto = new FileDto();
$fileDto->fillFromObject($fileEntity);
$this->fileDtoList[] = $fileDto;
}
}
if ($gameEntity->getGameDateTime() !== null)
{
$this->gameDateTime = new \DateTime($gameEntity->getGameDateTime()->format('Y-m-d H:i:s'));
}
if ($gameEntity->getCreatedAt() !== null)
{
$this->createdAt = $gameEntity->getCreatedAt();
}
if ($gameEntity->getUpdatedAt() !== null)
{
$this->createdAt = $gameEntity->getUpdatedAt();
}
if ($gameEntity->getPlannedDate() !== null)
{
$this->plannedDate = new \DateTime($gameEntity->getPlannedDate()->format('Y-m-d H:i:s'));
}
if ($gameEntity->getNotes() !== null)
{
$this->notes = $gameEntity->getNotes();
}
if ($gameEntity->getNotes() !== null)
{
$this->notes = $gameEntity->getNotes();
}
if ($gameEntity->getPointsAway() !== null)
{
$this->pointsAway = $gameEntity->getPointsAway();
}
if ($gameEntity->getPointsHome() !== null)
{
$this->pointsAway = $gameEntity->getPointsHome();
}
}
public function validate(): void
{
if (empty($this->name))
{
$this->validationErrors[] = 'El nombre no puede estar vacío.';
}
if (
empty($this->pointsPerWin)
)
{
$this->validationErrors[] = 'Los puntos por partido ganado no pueden estar vacíos.';
}
if (
isset($this->pointsPerDraw, $this->pointsPerWin, $this->pointsPerLoss) &&
(($this->pointsPerWin <= $this->pointsPerDraw) ||
($this->pointsPerWin <= $this->pointsPerLoss))
)
{
$this->validationErrors[] = 'Los puntos por partido ganado deben ser superiores a los puntos por empate y por perdida.';
}
if (($this->pointsPerDraw > $this->pointsPerWin))
{
$this->validationErrors[] = 'Los puntos por empate deben ser inferiores a los puntos por partido ganado.';
}
if (($this->pointsPerDraw < $this->pointsPerLoss))
{
$this->validationErrors[] = 'Los puntos por empate deben ser superiores a los puntos por partido perdido.';
}
if ($this->pointsPerWin + $this->pointsPerDraw + $this->pointsPerLoss > 20)
{
$this->validationErrors[] = 'La suma de los puntos por partidos ganados, perdidos y empatados no puede ser superior a 20.';
}
}
}
+220
View File
@@ -0,0 +1,220 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Exception\ValidationException;
use DMD\LaLigaApi\Entity\League;
class LeagueDto
{
public int $id;
public string $name;
public string $city;
public string $logo;
public string $description;
public int $pointsPerWin;
public int $pointsPerDraw;
public int $pointsPerLoss;
public int $matchesBetweenTeams;
public array $blockedMatchDates;
public bool $active;
public array $seasonDtoList;
public int $presidentId;
public bool $isPublic;
public \DateTimeImmutable $createdAt;
public array $validationErrors;
public function toArray(): array
{
$seasonIdList = [];
if (!empty($this->seasonDtoList))
{
foreach ($this->seasonDtoList as $seasonDto)
{
$seasonIdList[] = $seasonDto->id;
}
}
return [
'id' => $this->id ?? null,
'name' => $this->name ?? null,
'logo' => $this->logo ?? null,
'description' => $this->description ?? null,
'pointsPerWin' => $this->pointsPerWin ?? null,
'pointsPerDraw' => $this->pointsPerDraw ?? null,
'pointsPerLoss' => $this->pointsPerLoss ?? null,
'matchesBetweenTeams' => $this->matchesBetweenTeams ?? [],
'blockedMatchDates' => $this->blockedMatchDates ?? [],
'active' => $this->active ?? null,
'isPublic' => $this->isPublic ?? null,
'seasonIdList' => $seasonIdList,
'presidentId' => $this->presidentId ?? null,
'createdAt' => !empty($this->createdAt) ? $this->createdAt->format('Y-m-d H:i:s') : null
];
}
public function fillFromArray(array $dataList): void
{
if (isset($dataList['id']))
{
$this->id = $dataList['id'];
}
if (!empty($dataList['name']))
{
$this->name = $dataList['name'];
}
if (!empty($dataList['city']))
{
$this->city = $dataList['city'];
}
if (!empty($dataList['logo']))
{
$this->logo = $dataList['logo'];
}
if (!empty($dataList['description']))
{
$this->description = $dataList['description'];
}
if (isset($dataList['pointsPerWin']))
{
$this->pointsPerWin = (int) $dataList['pointsPerWin'];
}
if (isset($dataList['pointsPerDraw']))
{
$this->pointsPerDraw = (int) $dataList['pointsPerDraw'];
}
if (isset($dataList['pointsPerLoss']))
{
$this->pointsPerLoss = (int) $dataList['pointsPerLoss'];
}
if (isset($dataList['matchesBetweenTeams']))
{
$this->matchesBetweenTeams = (int) $dataList['matchesBetweenTeams'];
}
if (isset($dataList['blockedMatchDates']))
{
$this->blockedMatchDates = $dataList['blockedMatchDates'];
}
if (!empty($dataList['seasonList']))
{
foreach ($dataList['seasonList'] as $seasonItem)
{
$seasonDto = new SeasonDto();
$seasonDto->fillFromArray($seasonItem);
$this->seasonDtoList[] = $seasonDto;
}
}
if (isset($dataList['isPublic']))
{
$this->isPublic = (bool) $dataList['isPublic'];
}
if (!empty($dataList['createdAt']))
{
$this->createdAt = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dataList['createdAt']);
}
}
public function fillFromObject(League $leagueObj): void
{
if ($leagueObj->getId() !== null)
{
$this->id = $leagueObj->getId();
}
if ($leagueObj->getName() !== null)
{
$this->name = $leagueObj->getName();
}
if ($leagueObj->getCity() !== null)
{
$this->city = $leagueObj->getCity();
}
if ($leagueObj->getDescription() !== null)
{
$this->description = $leagueObj->getDescription();
}
if ($leagueObj->getLogo() !== null)
{
$this->logo = $leagueObj->getLogo();
}
if ($leagueObj->getPointsPerWin() !== null)
{
$this->pointsPerWin = $leagueObj->getPointsPerWin();
}
if ($leagueObj->getPointsPerDraw() !== null)
{
$this->pointsPerDraw = $leagueObj->getPointsPerDraw();
}
if ($leagueObj->getPointsPerLoss() !== null)
{
$this->pointsPerLoss = $leagueObj->getPointsPerLoss();
}
if ($leagueObj->getMatchesBetweenTeams() !== null)
{
$this->matchesBetweenTeams = $leagueObj->getMatchesBetweenTeams();
}
if ($leagueObj->getBlockedMatchDates() !== null)
{
$this->blockedMatchDates = $leagueObj->getBlockedMatchDates();
}
if ($leagueObj->getCreatedAt() !== null)
{
$this->createdAt = $leagueObj->getCreatedAt();
}
if ($leagueObj->isPublic() !== null)
{
$this->isPublic = $leagueObj->isPublic();
}
if ($leagueObj->getSeasons() !== null)
{
foreach ($leagueObj->getSeasons() as $seasonObj)
{
$seasonDto = new SeasonDto();
$seasonDto->fillFromObject($seasonObj);
$this->seasonDtoList[] = $seasonDto;
}
}
}
/**
* @throws ValidationException
*/
public function validate(): void
{
if (empty($this->name))
{
$this->validationErrors[] = 'El nombre no puede estar vacío.';
}
if (empty($this->city))
{
$this->validationErrors[] = 'La localidad no puede estar vacía.';
}
if (empty($this->pointsPerWin))
{
$this->validationErrors[] = 'Los puntos por partido ganado no pueden estar vacíos.';
}
if (
isset($this->pointsPerDraw, $this->pointsPerWin, $this->pointsPerLoss) &&
(($this->pointsPerWin <= $this->pointsPerDraw) ||
($this->pointsPerWin <= $this->pointsPerLoss))
)
{
$this->validationErrors[] = 'Los puntos por partido ganado deben ser superiores a los puntos por empate y por perdida.';
}
if (($this->pointsPerDraw > $this->pointsPerWin))
{
$this->validationErrors[] = 'Los puntos por empate deben ser inferiores a los puntos por partido ganado.';
}
if (($this->pointsPerDraw < $this->pointsPerLoss))
{
$this->validationErrors[] = 'Los puntos por empate deben ser superiores a los puntos por partido perdido.';
}
if ($this->pointsPerWin + $this->pointsPerDraw + $this->pointsPerLoss > 20)
{
$this->validationErrors[] = 'La suma de los puntos por partidos ganados, perdidos y empatados no puede ser superior a 20.';
}
if (!empty($this->validationErrors))
{
throw new ValidationException($this->validationErrors);
}
}
}
+137
View File
@@ -0,0 +1,137 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Entity\Notification;
class NotificationDto
{
public static string $TYPE_JOIN_LEAGUE = 'joinLeague';
public static string $TYPE_JOIN_TEAM = 'joinTeam';
public static string $TYPE_CAPTAIN_REQUEST = 'captainRequest';
public int $id;
public string $type;
public string $message;
public int $teamId;
public int $leagueId;
public int $userWhoFiredEventId;
public int $userToNotifyId;
public bool $isRead;
public \DateTimeImmutable $readAt;
public \DateTimeImmutable $createdAt;
public function toArray(): array
{
return [
'id' => $this->id ?? '',
'type' => $this->type ?? '',
'message' => $this->message ?? '',
'teamId' => $this->teamId ?? '',
'leagueId' => $this->leagueId ?? '',
'isRead' => $this->isRead ?? false,
'readAt' => !empty($this->readAt) ? $this->readAt->format('Y-m-d H:i:s') : '',
'createdAt' => !empty($this->createdAt) ? $this->createdAt->format('Y-m-d H:i:s') : ''
];
}
public function fillFromArray(array $dataList): void
{
if (isset($dataList['id']))
{
$this->id = $dataList['id'];
}
if (!empty($dataList['type']))
{
$this->type = match($dataList['type']) {
self::$TYPE_JOIN_LEAGUE => 'JOIN_LEAGUE',
self::$TYPE_JOIN_TEAM => 'JOIN_TEAM',
self::$TYPE_CAPTAIN_REQUEST => 'CAPTAIN_REQUEST',
default => null
};
}
if (!empty($dataList['message']))
{
$this->message = $dataList['message'];
}
if (!empty($dataList['isRead']))
{
$this->isRead = $dataList['isRead'];
}
if (!empty($dataList['readAt']))
{
$this->readAt = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dataList['readAt']);
}
if (!empty($dataList['createdAt']))
{
$this->createdAt = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dataList['createdAt']);
}
if (isset($dataList['teamId']))
{
$this->teamId = (int) $dataList['teamId'];
}
if (isset($dataList['userWhoFiredEventId']))
{
$this->userWhoFiredEventId = $dataList['userWhoFiredEventId'];
}
if (isset($dataList['userToNotifyId']))
{
$this->userToNotifyId = $dataList['userToNotifyId'];
}
if (isset($dataList['leagueId']))
{
$this->leagueId = $dataList['leagueId'];
}
}
public function fillFromObj(Notification $notificationObj): self
{
if ($notificationObj->getId() !== null)
{
$this->id = $notificationObj->getId();
}
if ($notificationObj->getType() !== null)
{
$this->type = $notificationObj->getType();
}
if ($notificationObj->getMessage() !== null)
{
$this->message = $notificationObj->getMessage();
}
if ($notificationObj->getUserWhoFiredEvent() !== null)
{
$this->userWhoFiredEventId = ($notificationObj->getUserWhoFiredEvent())->getId();
}
if ($notificationObj->getUserToNotify() !== null)
{
$this->userToNotifyId = ($notificationObj->getUserToNotify())->getId();
}
if ($notificationObj->getLeague() !== null)
{
$this->leagueId = ($notificationObj->getLeague())->getId();
}
if ($notificationObj->getTeamId() !== null)
{
$this->teamId = $notificationObj->getTeamId();
}
if ($notificationObj->isIsRead() !== null)
{
$this->isRead = $notificationObj->isIsRead();
}
if ($notificationObj->getReadAt() !== null)
{
$this->readAt = $notificationObj->getReadAt();
}
if ($notificationObj->getCreatedAt() !== null)
{
$this->createdAt = $notificationObj->getCreatedAt();
}
return $this;
}
public function validate(): void
{
}
}
+127
View File
@@ -0,0 +1,127 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Entity\Player;
class PlayerDto
{
public int $id;
public string $firstName;
public string $lastName;
public string $position;
public int $jerseyNumber;
public bool $isFederated;
public string $pictureFileName;
public \DateTime $birthday;
public array $fileDtoList;
public TeamDto $teamDto;
public \DateTime $createdAt;
public function fillFromArray(array $dataList): void
{
if (isset($dataList['id']))
{
$this->id = $dataList['id'];
}
if (!empty($dataList['firstName']))
{
$this->firstName = $dataList['firstName'];
}
if (!empty($dataList['lastName']))
{
$this->lastName = $dataList['lastName'];
}
if (!empty($dataList['position']))
{
$this->position = $dataList['position'];
}
if (!isset($dataList['jerseyNumber']))
{
$this->jerseyNumber = (int) $dataList['jerseyNumber'];
}
if (isset($dataList['isFederated']))
{
$this->isFederated = (bool) $dataList['isFederated'];
}
if (isset($dataList['pictureFileName']))
{
$this->pictureFileName = $dataList['pictureFileName'];
}
if (!empty($dataList['birthday']))
{
$this->birthday = \DateTime::createFromFormat('Y-m-d', $dataList['birthday']);
}
if (!empty($dataList['fileList']))
{
foreach ($dataList['fileList'] as $fileItem)
{
$fileDto = new FileDto();
$fileDto->fillFromArray($fileItem);
$this->fileDtoList[] = $fileDto;
}
}
if (!empty($dataList['team']))
{
$teamDto = new TeamDto();
$teamDto->fillFromArray($dataList['team']);
$this->teamDto = $teamDto;
}
if (!empty($dataList['createdAt']))
{
$this->createdAt = \DateTime::createFromFormat('Y-m-d H:i:s', $dataList['createdAt']);
}
}
public function fillFromObject(Player $playerEntity): void
{
if ($playerEntity->getId() !== null)
{
$this->id = $playerEntity->getId();
}
if ($playerEntity->getFirstName() !== null)
{
$this->firstName = $playerEntity->getFirstName();
}
if ($playerEntity->getLastName() !== null)
{
$this->lastName = $playerEntity->getLastName();
}
if ($playerEntity->getBirthday() !== null)
{
$this->birthday = new \DateTime($playerEntity->getBirthday()->format('Y-m-d'),new \DateTimeZone('Europe/Madrid'));
}
if ($playerEntity->getJerseyNumber() !== null)
{
$this->jerseyNumber = $playerEntity->getJerseyNumber();
}
if ($playerEntity->getPosition() !== null)
{
$this->position = $playerEntity->getPosition();
}
if ($playerEntity->getPictureFileName() !== null)
{
$this->pictureFileName = $playerEntity->getPictureFileName();
}
if ($playerEntity->getTeam() !== null)
{
$teamDto = new TeamDto();
$teamDto->fillFromObject($playerEntity->getTeam());
$this->teamDto = $teamDto;
}
if ($playerEntity->getFiles() !== null)
{
foreach ($playerEntity->getFiles() as $fileEntity)
{
$fileDto = new FileDto();
$fileDto->fillFromObject($fileEntity);
$this->fileDtoList[] = $fileDto;
}
}
}
public function validate(): void
{
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace DMD\LaLigaApi\Dto;
class SeasonDataDto
{
public int $id;
public int $teamId;
public int $points;
public int $seasonId;
public function fillFromArray(array $dataList): void
{
if (isset($dataList['id']))
{
$this->id = (int) $dataList['id'];
}
if (isset($dataList['teamId']))
{
$this->teamId = $dataList['teamId'];
}
if (isset($dataList['points']))
{
$this->points = $dataList['points'];
}
if (isset($dataList['seasonId']))
{
$this->seasonId = $dataList['seasonId'];
}
}
}
+126
View File
@@ -0,0 +1,126 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Entity\Season;
use DMD\LaLigaApi\Exception\ValidationException;
class SeasonDto
{
public int $id;
public \DateTime $dateStart;
public array $teamDtoList;
public array $facilityDtoList;
public int $leagueId;
public array $gameDtoList;
public array $seasonDataDtoList;
public bool $active;
public array $validationErrors;
public function toArray(): array
{
$teamList = [];
$facilityList = [];
if (!empty($this->teamDtoList))
{
foreach ($this->teamDtoList as $teamDto)
{
$teamList[] = $teamDto->toArray();
}
}
if (!empty($this->facilityDtoList))
{
foreach ($this->facilityDtoList as $facilityDto)
{
$facilityList[] = $facilityDto->toArray();
}
}
return [
'id' => $this->id ?? null,
'dateStart' => !empty($this->dateStart) ? $this->dateStart->format('Y-m'): null,
'leagueId' => $this->leagueId ?? null,
'teamList' => $teamList,
'facilityList' => $facilityList,
'active' => $this->active ?? null
];
}
public function fillFromArray(array $dataList): void
{
if (isset($dataList['id']))
{
$this->id = (int) $dataList['id'];
}
if (!empty($dataList['dateStart']))
{
$dateStart = \DateTime::createFromFormat('Y-m' ,$dataList['dateStart']);
if ($dateStart)
{
$this->dateStart = $dateStart;
}
}
if (isset($dataList['active']))
{
$this->active = $dataList['active'];
}
if (isset($dataList['teamList']))
{
foreach ($dataList['teamList'] as $teamName)
{
$teamDto = new TeamDto();
$teamDto->name = $teamName;
$this->teamDtoList[] = $teamDto;
}
}
if (!empty($dataList['facilityList']))
{
foreach ($dataList['facilityList'] as $facilityItem)
{
$facilityDto = new FacilityDto();
$facilityDto->fillFromArray($facilityItem);
$this->facilityDtoList[] = $facilityDto;
}
}
if (isset($dataList['gameList']))
{
foreach ($dataList['gameList'] as $gameItem)
{
$gameDto = new GameDto();
$gameDto->fillFromArray($gameItem);
$this->gameDtoList[] = $gameDto;
}
}
}
public function fillFromObject(Season $seasonObj): void
{
if ($seasonObj->getId() !== null)
{
$this->id = $seasonObj->getId();
}
if ($seasonObj->getDateStart() !== null)
{
$this->dateStart = $seasonObj->getDateStart();
}
$leagueObj = $seasonObj->getLeague();
if ($leagueObj !== null)
{
$this->leagueId = $leagueObj->getId();
}
if ($leagueObj->isActive() !== null)
{
$this->active = $leagueObj->isActive();
}
}
/**
* @throws ValidationException
*/
public function validate(): void
{
if (!empty($this->validationErrors))
{
throw new ValidationException($this->validationErrors);
}
}
}
+127
View File
@@ -0,0 +1,127 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Entity\Facility;
use DMD\LaLigaApi\Entity\Team;
use DMD\LaLigaApi\Exception\ValidationException;
class TeamDto
{
public int $id;
public string $name;
public bool $active;
public array $seasonDtoList;
public array $playerDtoList;
public array $validationErrors;
public UserDto $captainDto;
public \DateTimeImmutable $createdAt;
public function toArray(): array
{
$seasonList = [];
$playerList = [];
if (!empty($this->seasonDtoList))
{
foreach ($this->seasonDtoList as $seasonDto)
{
$seasonList = $seasonDto->toArray();
}
}
if (!empty($this->playerDtoList))
{
foreach ($this->playerDtoList as $playerDto)
{
$playerList = $playerDto->toArray();
}
}
return [
'name' => $this->name ?? '',
'playerList' => $playerList,
'seasonList' => $seasonList,
'captainId' => $this->captainDto?->id,
'createdAt' => $this->createdAt->format('Y-m-d')
];
}
public function fillFromArray(array $dataList): void
{
if (isset($dataList['id']))
{
$this->id = $dataList['id'];
}
if (!empty($dataList['name']))
{
$this->name = $dataList['name'];
}
if (isset($dataList['active']))
{
$this->active = $dataList['active'];
}
if (!empty($dataList['seasonList']))
{
foreach ($dataList['seasonList'] as $seasonItem)
{
$seasonDto = new SeasonDto();
$seasonDto->fillFromArray($seasonItem);
$this->seasonDtoList[] = $seasonDto;
}
}
if (!empty($dataList['playerList']))
{
foreach ($dataList['playerList'] as $playerItem)
{
$playerDto = new PlayerDto();
$playerDto->fillFromArray($playerItem);
$this->playerDtoList[] = $playerDto;
}
}
if (!empty($dataList['captain']))
{
$captainDto = new UserDto();
$captainDto->fillFromArray($dataList['captain']);
$this->captainDto = $captainDto;
}
if (!empty($dataList['createdAt']))
{
$this->createdAt = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dataList['createdAt'], new \DateTimeZone('Europe/Madrid'));
}
}
public function fillFromObject(Team $teamEntity): void
{
if ($teamEntity->getId())
{
$this->id = $teamEntity->getId();
}
if ($teamEntity->getName())
{
$this->name = $teamEntity->getName();
}
if ($teamEntity->getPlayers())
{
foreach ($teamEntity->getPlayers() as $playerEntity)
{
$playerDto = new PlayerDto();
$playerDto->fillFromObject($playerEntity);
$this->playerDtoList[] = $playerDto;
}
}
if ($teamEntity->getCreatedAt())
{
$this->createdAt = $teamEntity->getCreatedAt();
}
}
public function validate(): void
{
if (empty($this->name))
{
$this->validationErrors[] = 'El nombre del equipo no puede estar vacío.';
}
if (!empty($this->validationErrors))
{
throw new ValidationException($this->validationErrors);
}
}
}
+164
View File
@@ -0,0 +1,164 @@
<?php
namespace DMD\LaLigaApi\Dto;
use DMD\LaLigaApi\Entity\User;
class UserDto
{
public int $id;
public array $roles;
public string $email;
public string $password;
public string $firstName;
public string $lastName;
public string $phone;
public string $profilePicture;
public \DateTimeInterface $birthday;
public array $noteList;
public bool $active;
public array $notificationDtoList;
public array $validationErrors;
public function toArray(): array
{
if (!empty($this->notificationDtoList))
{
foreach ($this->notificationDtoList as $notificationDto)
{
$notificationArray[] = $notificationDto->toArray();
}
}
return [
'id' => $this->id ?? null,
'email' => $this->email ?? null,
'firstName' => $this->firstName ?? null,
'lastName' => $this->lastName ?? null,
'phone' => $this->phone,
'profilePicture' => $this->profilePicture ?? null,
'birthday' => $this->birthday->format('Y-m-d'),
'noteList' => $this->noteList ?? [],
'notificationList' => $notificationArray ?? []
];
}
public function fillFromObject(User $userObj): void
{
if ($userObj->getId() !== null)
{
$this->id = $userObj->getId();
}
if ($userObj->getEmail() !== null)
{
$this->email = $userObj->getEmail();
}
if ($userObj->getFirstName() !== null)
{
$this->firstName = $userObj->getFirstName();
}
if ($userObj->getLastName() !== null)
{
$this->lastName = $userObj->getLastName();
}
if ($userObj->getPhone() !== null)
{
$this->phone = $userObj->getPhone();
}
if ($userObj->getProfilePicture() !== null)
{
$this->profilePicture = $userObj->getProfilePicture();
}
if ($userObj->getBirthday() !== null)
{
$this->birthday = $userObj->getBirthday();
}
if ($userObj->getNoteList() !== null)
{
$this->noteList = $userObj->getNoteList();
}
}
public function fillFromArray(array $dataList): void
{
if (!empty($dataList['id']))
{
$this->id = $dataList['id'];
}
if (!empty($dataList['email']))
{
$this->email = trim($dataList['email']);
}
if (!empty($dataList['password']))
{
$this->password = trim($dataList['password']);
}
if (!empty($dataList['firstName']))
{
$this->firstName = $dataList['firstName'];
}
if (!empty($dataList['lastName']))
{
$this->lastName = $dataList['lastName'];
}
if (!empty($dataList['phone']))
{
$this->phone = $dataList['phone'];
}
if (!empty($dataList['profilePicture']))
{
$this->profilePicture = $dataList['profilePicture'];
}
if (!empty($dataList['birthday']))
{
$this->birthday = \DateTime::createFromFormat('Y-m-d', $dataList['birthday']);
}
if (!empty($dataList['notes']))
{
$this->noteList = $dataList['notes'];
}
if (isset($dataList['active']))
{
$this->active = $dataList['active'];
}
}
public function validate(): void
{
if (empty($this->email))
{
$this->validationErrors[] = 'El correo no puede estar vacío.';
}
if (!empty($this->email) && !(filter_var($this->email, FILTER_VALIDATE_EMAIL)))
{
$this->validationErrors[] = 'El correo no está en un formato válido.';
}
if (empty($this->firstName))
{
$this->validationErrors[] = 'El nombre no puede estar vacío';
}
if (empty($this->lastName))
{
$this->validationErrors[] = 'El apellido no puede estar vacío';
}
if (strlen($this->phone) !== 9)
{
$this->validationErrors[] = 'El número de teléfono debe tener 9 dígitos.';
}
if (!preg_match('@[A-Z]@', $this->password))
{
$this->validationErrors[] = 'La contraseña debe contener al menos una letra mayúscula.';
}
if (!preg_match('@[0-9]@', $this->password))
{
$this->validationErrors[] = 'La contraseña debe contener al menos un número.';
}
if (!preg_match('@\W@', $this->password))
{
$this->validationErrors[] = 'La contraseña debe contener al menos un caracter especial.';
}
if (strlen($this->password) < 8)
{
$this->validationErrors[] = 'La contraseña debe contener al menos 8 caracteres.';
}
}
}
View File
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: CustomRoleRepository::class)]
#[ORM\HasLifecycleCallbacks]
class CustomRole
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $name = null;
#[ORM\ManyToOne(inversedBy: 'customRoles')]
private ?User $user = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
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 getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): static
{
$this->user = $user;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
#[ORM\PrePersist]
public function setCreatedAt(): static
{
$this->createdAt = new \DateTimeImmutable('now', new \DateTimeZone('Europe/Madrid'));
return $this;
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\FacilityRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: FacilityRepository::class)]
#[ORM\HasLifecycleCallbacks]
class Facility
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $name = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $address = null;
#[ORM\OneToMany(mappedBy: 'facility', targetEntity: Game::class)]
private Collection $games;
#[ORM\ManyToOne(inversedBy: 'facilities')]
private ?Season $season = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
public function __construct()
{
$this->games = new ArrayCollection();
}
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 getAddress(): ?string
{
return $this->address;
}
public function setAddress(?string $address): static
{
$this->address = $address;
return $this;
}
/**
* @return Collection<int, Game>
*/
public function getGames(): Collection
{
return $this->games;
}
public function addGame(Game $game): static
{
if (!$this->games->contains($game)) {
$this->games->add($game);
$game->setFacility($this);
}
return $this;
}
public function removeGame(Game $game): static
{
if ($this->games->removeElement($game)) {
// set the owning side to null (unless already changed)
if ($game->getFacility() === $this) {
$game->setFacility(null);
}
}
return $this;
}
public function getSeason(): ?Season
{
return $this->season;
}
public function setSeason(?Season $season): static
{
$this->season = $season;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
#[ORM\PrePersist]
public function setCreatedAt(): void
{
$timezone = new \DateTimeZone('Europe/Madrid');
$this->createdAt = new \DateTimeImmutable('now', $timezone);
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\FileRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: FileRepository::class)]
#[ORM\HasLifecycleCallbacks]
class File
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $name = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $type = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\ManyToOne(inversedBy: 'files')]
private ?Game $game = null;
#[ORM\ManyToOne(inversedBy: 'files')]
private ?Player $player = null;
#[ORM\ManyToOne(inversedBy: 'files')]
private ?Season $season = null;
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 getType(): ?string
{
return $this->type;
}
public function setType(?string $type): static
{
$this->type = $type;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
#[ORM\PrePersist]
public function setCreatedAt(): void
{
$timezone = new \DateTimeZone('Europe/Madrid');
$this->createdAt = new \DateTimeImmutable('now', $timezone);
}
public function getGame(): ?Game
{
return $this->game;
}
public function setGame(?Game $game): static
{
$this->game = $game;
return $this;
}
public function getPlayer(): ?Player
{
return $this->player;
}
public function setPlayer(?Player $player): static
{
$this->player = $player;
return $this;
}
public function getSeason(): ?Season
{
return $this->season;
}
public function setSeason(?Season $season): static
{
$this->season = $season;
return $this;
}
}
+227
View File
@@ -0,0 +1,227 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\GameRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: GameRepository::class)]
class Game
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(nullable: true)]
private ?int $pointsHome = null;
#[ORM\Column(nullable: true)]
private ?int $pointsAway = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTimeInterface $plannedDate = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTimeInterface $gameDateTime = null;
#[ORM\Column(length: 350, nullable: true)]
private ?string $notes = null;
#[ORM\OneToMany(mappedBy: 'game', targetEntity: File::class)]
private Collection $files;
#[ORM\ManyToOne(inversedBy: 'games')]
private ?Season $season = null;
#[ORM\ManyToOne(inversedBy: 'games')]
private ?Facility $facility = null;
#[ORM\ManyToOne]
private ?Team $homeTeam = null;
#[ORM\ManyToOne]
private ?Team $awayTeam = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $updatedAt = null;
public function __construct()
{
$this->files = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getPointsHome(): ?int
{
return $this->pointsHome;
}
public function setPointsHome(?int $pointsHome): static
{
$this->pointsHome = $pointsHome;
return $this;
}
public function getPointsAway(): ?int
{
return $this->pointsAway;
}
public function setPointsAway(?int $pointsAway): static
{
$this->pointsAway = $pointsAway;
return $this;
}
public function getPlannedDate(): ?\DateTimeInterface
{
return $this->plannedDate;
}
public function setPlannedDate(?\DateTimeInterface $plannedDate): static
{
$this->plannedDate = $plannedDate;
return $this;
}
public function getGameDateTime(): ?\DateTimeInterface
{
return $this->gameDateTime;
}
public function setGameDateTime(?\DateTimeInterface $gameDateTime): static
{
$this->gameDateTime = $gameDateTime;
return $this;
}
public function getNotes(): ?string
{
return $this->notes;
}
public function setNotes(?string $notes): static
{
$this->notes = $notes;
return $this;
}
/**
* @return Collection<int, File>
*/
public function getFiles(): Collection
{
return $this->files;
}
public function addFile(File $file): static
{
if (!$this->files->contains($file)) {
$this->files->add($file);
$file->setGame($this);
}
return $this;
}
public function removeFile(File $file): static
{
if ($this->files->removeElement($file)) {
// set the owning side to null (unless already changed)
if ($file->getGame() === $this) {
$file->setGame(null);
}
}
return $this;
}
public function getSeason(): ?Season
{
return $this->season;
}
public function setSeason(?Season $season): static
{
$this->season = $season;
return $this;
}
public function getFacility(): ?Facility
{
return $this->facility;
}
public function setFacility(?Facility $facility): static
{
$this->facility = $facility;
return $this;
}
public function getHomeTeam(): ?Team
{
return $this->homeTeam;
}
public function setHomeTeam(?Team $homeTeam): static
{
$this->homeTeam = $homeTeam;
return $this;
}
public function getAwayTeam(): ?Team
{
return $this->awayTeam;
}
public function setAwayTeam(?Team $awayTeam): static
{
$this->awayTeam = $awayTeam;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
#[ORM\PrePersist]
public function setCreatedAt(): static
{
$this->createdAt = new \DateTimeImmutable('now');
return $this;
}
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTimeImmutable $updatedAt): static
{
$this->updatedAt = $updatedAt;
return $this;
}
}
+244
View File
@@ -0,0 +1,244 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\LeagueRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: LeagueRepository::class)]
#[ORM\HasLifecycleCallbacks]
class League
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $name = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $logo = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $description = null;
#[ORM\Column(nullable: true)]
private ?bool $active = null;
#[ORM\OneToMany(mappedBy: 'league', targetEntity: Season::class)]
private Collection $seasons;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\Column(nullable: true)]
private ?int $pointsPerWin = null;
#[ORM\Column(nullable: true)]
private ?int $pointsPerDraw = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $city = null;
#[ORM\Column(nullable: true)]
private ?int $pointsPerLoss = null;
#[ORM\Column(nullable: true)]
private ?int $matchesBetweenTeams = null;
#[ORM\Column(type: Types::JSON, nullable: true)]
private ?array $blockedMatchDates = null;
#[ORM\Column(nullable: true)]
private ?bool $isPublic = null;
public function __construct()
{
$this->seasons = new ArrayCollection();
}
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 getLogo(): ?string
{
return $this->logo;
}
public function setLogo(?string $logo): static
{
$this->logo = $logo;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->description = $description;
return $this;
}
public function isActive(): ?bool
{
return $this->active;
}
public function setActive(?bool $active): static
{
$this->active = $active;
return $this;
}
/**
* @return Collection<int, Season>
*/
public function getSeasons(): Collection
{
return $this->seasons;
}
public function addSeason(Season $season): static
{
if (!$this->seasons->contains($season)) {
$this->seasons->add($season);
$season->setLeague($this);
}
return $this;
}
public function removeSeason(Season $season): static
{
if ($this->seasons->removeElement($season)) {
// set the owning side to null (unless already changed)
if ($season->getLeague() === $this) {
$season->setLeague(null);
}
}
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
#[ORM\PrePersist]
public function setCreatedAt(): void
{
$timezone = new \DateTimeZone('Europe/Madrid');
$this->createdAt = new \DateTimeImmutable('now', $timezone);
}
public function getPointsPerWin(): ?int
{
return $this->pointsPerWin;
}
public function setPointsPerWin(?int $pointsPerWin): static
{
$this->pointsPerWin = $pointsPerWin;
return $this;
}
public function getPointsPerDraw(): ?int
{
return $this->pointsPerDraw;
}
public function setPointsPerDraw(?int $pointsPerDraw): static
{
$this->pointsPerDraw = $pointsPerDraw;
return $this;
}
public function getCity(): ?string
{
return $this->city;
}
public function setCity(?string $city): static
{
$this->city = $city;
return $this;
}
public function getPointsPerLoss(): ?int
{
return $this->pointsPerLoss;
}
public function setPointsPerLoss(?int $pointsPerLoss): static
{
$this->pointsPerLoss = $pointsPerLoss;
return $this;
}
public function getMatchesBetweenTeams(): ?int
{
return $this->matchesBetweenTeams;
}
public function setMatchesBetweenTeams(?int $matchesBetweenTeams): static
{
$this->matchesBetweenTeams = $matchesBetweenTeams;
return $this;
}
public function getBlockedMatchDates(): ?array
{
return $this->blockedMatchDates;
}
public function setBlockedMatchDates(?array $blockedMatchDates): static
{
$this->blockedMatchDates = $blockedMatchDates;
return $this;
}
public function isPublic(): ?bool
{
return $this->isPublic;
}
public function setIsPublic(?bool $isPublic): static
{
$this->isPublic = $isPublic;
return $this;
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\LogRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: LogRepository::class)]
#[ORM\HasLifecycleCallbacks]
class Log
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $payload = null;
#[ORM\Column(nullable: true)]
private ?int $code = null;
#[ORM\Column(length: 550, nullable: true)]
private ?string $message = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
public function getId(): ?int
{
return $this->id;
}
public function getPayload(): ?string
{
return $this->payload;
}
public function setPayload(?string $payload): static
{
$this->payload = $payload;
return $this;
}
public function getCode(): ?int
{
return $this->code;
}
public function setCode(?int $code): static
{
$this->code = $code;
return $this;
}
public function getMessage(): ?string
{
return $this->message;
}
public function setMessage(?string $message): static
{
$this->message = $message;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
#[ORM\PrePersist]
public function setCreatedAt(): void
{
$timezone = new \DateTimeZone('Europe/Madrid');
$this->createdAt = new \DateTimeImmutable('now', $timezone);
}
}
+160
View File
@@ -0,0 +1,160 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\NotificationRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: NotificationRepository::class)]
#[ORM\HasLifecycleCallbacks]
class Notification
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $type = null;
#[ORM\ManyToOne(inversedBy: 'requestsSent')]
private ?User $userWhoFiredEvent = null;
#[ORM\Column(length: 280, nullable: true)]
private ?string $message = null;
#[ORM\ManyToOne(inversedBy: 'notifications')]
private ?League $league = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\Column(nullable: true)]
private ?int $teamId = null;
#[ORM\ManyToOne(inversedBy: 'receivedNotifications')]
#[ORM\JoinColumn(nullable: false)]
private ?User $userToNotify = null;
#[ORM\Column(nullable: true)]
private ?bool $isRead = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $readAt = null;
public function getId(): ?int
{
return $this->id;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(?string $type): static
{
$this->type = $type;
return $this;
}
public function getUserWhoFiredEvent(): ?User
{
return $this->userWhoFiredEvent;
}
public function setUserWhoFiredEvent(?User $userWhoFiredEvent): static
{
$this->userWhoFiredEvent = $userWhoFiredEvent;
return $this;
}
public function getMessage(): ?string
{
return $this->message;
}
public function setMessage(?string $message): static
{
$this->message = $message;
return $this;
}
public function getLeague(): ?League
{
return $this->league;
}
public function setLeague(?League $league): static
{
$this->league = $league;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
/**
* @throws \Exception
*/
#[ORM\PrePersist]
public function setCreatedAt(): static
{
$this->createdAt = new \DateTimeImmutable('now', new \DateTimeZone('Europe/Madrid'));
return $this;
}
public function getTeamId(): ?int
{
return $this->teamId;
}
public function setTeamId(?int $teamId): static
{
$this->teamId = $teamId;
return $this;
}
public function getUserToNotify(): ?User
{
return $this->userToNotify;
}
public function setUserToNotify(?User $userToNotify): static
{
$this->userToNotify = $userToNotify;
return $this;
}
public function isIsRead(): ?bool
{
return $this->isRead;
}
public function setIsRead(?bool $isRead): static
{
$this->isRead = $isRead;
return $this;
}
public function getReadAt(): ?\DateTimeImmutable
{
return $this->readAt;
}
public function setReadAt(?\DateTimeImmutable $readAt): static
{
$this->readAt = $readAt;
return $this;
}
}
+181
View File
@@ -0,0 +1,181 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\PlayerRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: PlayerRepository::class)]
class Player
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $firstName = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $lastName = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $position = null;
#[ORM\Column(type: Types::SMALLINT, nullable: true)]
private ?int $jerseyNumber = null;
#[ORM\Column(nullable: true)]
private ?bool $isFederated = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $pictureFileName = null;
#[ORM\Column(type: Types::DATE_MUTABLE, nullable: true)]
private ?\DateTimeInterface $birthday = null;
#[ORM\OneToMany(mappedBy: 'player', targetEntity: File::class)]
private Collection $files;
#[ORM\ManyToOne(inversedBy: 'players')]
private ?Team $team = null;
public function __construct()
{
$this->files = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(?string $firstName): static
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(?string $lastName): static
{
$this->lastName = $lastName;
return $this;
}
public function getPosition(): ?string
{
return $this->position;
}
public function setPosition(?string $position): static
{
$this->position = $position;
return $this;
}
public function getJerseyNumber(): ?int
{
return $this->jerseyNumber;
}
public function setJerseyNumber(?int $jerseyNumber): static
{
$this->jerseyNumber = $jerseyNumber;
return $this;
}
public function isIsFederated(): ?bool
{
return $this->isFederated;
}
public function setIsFederated(?bool $isFederated): static
{
$this->isFederated = $isFederated;
return $this;
}
public function getPictureFileName(): ?string
{
return $this->pictureFileName;
}
public function setPictureFileName(?string $pictureFileName): static
{
$this->pictureFileName = $pictureFileName;
return $this;
}
public function getBirthday(): ?\DateTimeInterface
{
return $this->birthday;
}
public function setBirthday(?\DateTimeInterface $birthday): static
{
$this->birthday = $birthday;
return $this;
}
/**
* @return Collection<int, File>
*/
public function getFiles(): Collection
{
return $this->files;
}
public function addFile(File $file): static
{
if (!$this->files->contains($file)) {
$this->files->add($file);
$file->setPlayer($this);
}
return $this;
}
public function removeFile(File $file): static
{
if ($this->files->removeElement($file)) {
// set the owning side to null (unless already changed)
if ($file->getPlayer() === $this) {
$file->setPlayer(null);
}
}
return $this;
}
public function getTeam(): ?Team
{
return $this->team;
}
public function setTeam(?Team $team): static
{
$this->team = $team;
return $this;
}
}
+245
View File
@@ -0,0 +1,245 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\SeasonRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: SeasonRepository::class)]
#[ORM\HasLifecycleCallbacks]
class Season
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: Types::DATE_MUTABLE)]
private ?\DateTimeInterface $dateStart = null;
#[ORM\Column(nullable: true)]
private ?bool $active = null;
#[ORM\ManyToMany(targetEntity: Team::class, inversedBy: 'seasons')]
private Collection $teams;
#[ORM\ManyToOne(inversedBy: 'seasons')]
private ?League $league = null;
#[ORM\OneToMany(mappedBy: 'season', targetEntity: Game::class)]
private Collection $games;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\OneToMany(mappedBy: 'season', targetEntity: Facility::class)]
private Collection $facilities;
#[ORM\Column(type: Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTimeInterface $updatedAt = null;
#[ORM\OneToMany(mappedBy: 'season', targetEntity: File::class)]
private Collection $files;
public function __construct()
{
$this->teams = new ArrayCollection();
$this->games = new ArrayCollection();
$this->facilities = new ArrayCollection();
$this->files = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* @return Collection<int, Team>
*/
public function getTeams(): Collection
{
return $this->teams;
}
public function addTeam(Team $team): static
{
if (!$this->teams->contains($team)) {
$this->teams->add($team);
}
return $this;
}
public function removeTeam(Team $team): static
{
$this->teams->removeElement($team);
return $this;
}
public function getDateStart(): ?\DateTimeInterface
{
return $this->dateStart;
}
public function setDateStart(\DateTimeInterface $dateStart): static
{
$this->dateStart = $dateStart;
return $this;
}
public function getDateEnd(): ?\DateTimeInterface
{
return $this->dateEnd;
}
public function setDateEnd(?\DateTimeInterface $dateEnd): static
{
$this->dateEnd = $dateEnd;
return $this;
}
public function isActive(): ?bool
{
return $this->active;
}
public function setActive(?bool $active): static
{
$this->active = $active;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
#[ORM\PrePersist]
public function setCreatedAt(): void
{
$timezone = new \DateTimeZone('Europe/Madrid');
$this->createdAt = new \DateTimeImmutable('now', $timezone);
}
public function getLeague(): ?League
{
return $this->league;
}
public function setLeague(?League $league): static
{
$this->league = $league;
return $this;
}
/**
* @return Collection<int, Game>
*/
public function getGames(): Collection
{
return $this->games;
}
public function addGame(Game $game): static
{
if (!$this->games->contains($game)) {
$this->games->add($game);
$game->setSeason($this);
}
return $this;
}
public function removeGame(Game $game): static
{
if ($this->games->removeElement($game)) {
// set the owning side to null (unless already changed)
if ($game->getSeason() === $this) {
$game->setSeason(null);
}
}
return $this;
}
/**
* @return Collection<int, Facility>
*/
public function getFacilities(): Collection
{
return $this->facilities;
}
public function addFacility(Facility $facility): static
{
if (!$this->facilities->contains($facility)) {
$this->facilities->add($facility);
$facility->setSeason($this);
}
return $this;
}
public function removeFacility(Facility $facility): static
{
if ($this->facilities->removeElement($facility)) {
// set the owning side to null (unless already changed)
if ($facility->getSeason() === $this) {
$facility->setSeason(null);
}
}
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTimeInterface $updatedAt): static
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* @return Collection<int, File>
*/
public function getFiles(): Collection
{
return $this->files;
}
public function addFile(File $file): static
{
if (!$this->files->contains($file)) {
$this->files->add($file);
$file->setSeason($this);
}
return $this;
}
public function removeFile(File $file): static
{
if ($this->files->removeElement($file)) {
// set the owning side to null (unless already changed)
if ($file->getSeason() === $this) {
$file->setSeason(null);
}
}
return $this;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\SeasonDataRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: SeasonDataRepository::class)]
class SeasonData
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(inversedBy: 'seasonData')]
private ?Team $team = null;
#[ORM\Column(nullable: true)]
private ?int $points = null;
#[ORM\ManyToOne(inversedBy: 'seasonData')]
private ?Season $season = null;
public function __construct()
{
}
public function getId(): ?int
{
return $this->id;
}
public function getTeam(): ?Team
{
return $this->team;
}
public function setTeam(?Team $team): static
{
$this->team = $team;
return $this;
}
public function getPoints(): ?int
{
return $this->points;
}
public function setSeasonPoints(?int $points): static
{
$this->points = $points;
return $this;
}
public function getSeason(): ?Season
{
return $this->season;
}
public function setSeason(?Season $season): static
{
$this->season = $season;
return $this;
}
public function setPoints(?int $points): static
{
$this->points = $points;
return $this;
}
}
+187
View File
@@ -0,0 +1,187 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\TeamRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: TeamRepository::class)]
#[ORM\HasLifecycleCallbacks]
class Team
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $name = null;
#[ORM\Column(nullable: true)]
private ?bool $active = null;
#[ORM\ManyToMany(targetEntity: Season::class, mappedBy: 'teams')]
private Collection $seasons;
#[ORM\OneToMany(mappedBy: 'team', targetEntity: SeasonData::class)]
private Collection $seasonData;
#[ORM\OneToMany(mappedBy: 'team', targetEntity: Player::class)]
private Collection $players;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\OneToOne(inversedBy: 'team', cascade: ['persist', 'remove'])]
private ?User $captain = null;
public function __construct()
{
$this->seasons = new ArrayCollection();
$this->seasonData = new ArrayCollection();
$this->players = new ArrayCollection();
}
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 isActive(): ?bool
{
return $this->active;
}
public function setActive(?bool $active): static
{
$this->active = $active;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
#[ORM\PrePersist]
public function setCreatedAt(): void
{
$this->createdAt = new \DateTimeImmutable();
}
/**
* @return Collection<int, Season>
*/
public function getSeasons(): Collection
{
return $this->seasons;
}
public function addSeason(Season $season): static
{
if (!$this->seasons->contains($season)) {
$this->seasons->add($season);
$season->addTeam($this);
}
return $this;
}
public function removeSeason(Season $season): static
{
if ($this->seasons->removeElement($season)) {
$season->removeTeam($this);
}
return $this;
}
/**
* @return Collection<int, SeasonData>
*/
public function getSeasonData(): Collection
{
return $this->seasonData;
}
public function addSeasonData(SeasonData $seasonData): static
{
if (!$this->seasonData->contains($seasonData)) {
$this->seasonData->add($seasonData);
$seasonData->setTeam($this);
}
return $this;
}
public function removeSeasonData(SeasonData $seasonData): static
{
if ($this->seasonData->removeElement($seasonData)) {
// set the owning side to null (unless already changed)
if ($seasonData->getTeam() === $this) {
$seasonData->setTeam(null);
}
}
return $this;
}
/**
* @return Collection<int, Player>
*/
public function getPlayers(): Collection
{
return $this->players;
}
public function addPlayer(Player $player): static
{
if (!$this->players->contains($player)) {
$this->players->add($player);
$player->setTeam($this);
}
return $this;
}
public function removePlayer(Player $player): static
{
if ($this->players->removeElement($player)) {
// set the owning side to null (unless already changed)
if ($player->getTeam() === $this) {
$player->setTeam(null);
}
}
return $this;
}
public function getCaptain(): ?User
{
return $this->captain;
}
public function setCaptain(?User $captain): static
{
$this->captain = $captain;
return $this;
}
}
+352
View File
@@ -0,0 +1,352 @@
<?php
namespace DMD\LaLigaApi\Entity;
use DMD\LaLigaApi\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\HasLifecycleCallbacks]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180, unique: true)]
private ?string $email = null;
#[ORM\Column]
private array $roles = [];
#[ORM\Column]
private ?string $password = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $firstName = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $lastName = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $phone = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $profilePicture = null;
#[ORM\Column(type: Types::DATE_MUTABLE, nullable: true)]
private ?\DateTimeInterface $birthday = null;
#[ORM\Column(nullable: true)]
private ?bool $active = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\Column(type: Types::ARRAY, nullable: true)]
private ?array $noteList = null;
#[ORM\OneToOne(mappedBy: 'captain', cascade: ['persist', 'remove'])]
private ?Team $team = null;
#[ORM\OneToMany(mappedBy: 'userWhoFiredEvent', targetEntity: Notification::class)]
private Collection $sentNotifications;
#[ORM\OneToMany(mappedBy: 'user', targetEntity: CustomRole::class, cascade: ['persist', 'remove'])]
private Collection $customRoles;
#[ORM\OneToMany(mappedBy: 'userToNotify', targetEntity: Notification::class, orphanRemoval: true)]
private Collection $receivedNotifications;
public function __construct()
{
$this->sentNotifications = new ArrayCollection();
$this->customRoles = new ArrayCollection();
$this->receivedNotifications = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): static
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): static
{
$this->roles = $roles;
return $this;
}
/**
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): static
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function eraseCredentials(): void
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(?string $firstName): static
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(?string $lastName): static
{
$this->lastName = $lastName;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(?string $phone): static
{
$this->phone = $phone;
return $this;
}
public function getProfilePicture(): ?string
{
return $this->profilePicture;
}
public function setProfilePicture(?string $profilePicture): static
{
$this->profilePicture = $profilePicture;
return $this;
}
public function getBirthday(): ?\DateTimeInterface
{
return $this->birthday;
}
public function setBirthday(?\DateTimeInterface $birthday): static
{
$this->birthday = $birthday;
return $this;
}
public function isActive(): ?bool
{
return $this->active;
}
public function setActive(?bool $active): static
{
$this->active = $active;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
#[ORM\PrePersist]
public function setCreatedAt(): void
{
$timezone = new \DateTimeZone('Europe/Madrid');
$this->createdAt = new \DateTimeImmutable('now', $timezone);
}
public function getNoteList(): ?array
{
return $this->noteList;
}
public function setNoteList(?array $noteList): static
{
$this->noteList = $noteList;
return $this;
}
public function getTeam(): ?Team
{
return $this->team;
}
public function setTeam(?Team $team): static
{
// unset the owning side of the relation if necessary
if ($team === null && $this->team !== null) {
$this->team->setCaptain(null);
}
// set the owning side of the relation if necessary
if ($team !== null && $team->getCaptain() !== $this) {
$team->setCaptain($this);
}
$this->team = $team;
return $this;
}
/**
* @return Collection<int, Notification>
*/
public function getSentNotifications(): Collection
{
return $this->sentNotifications;
}
public function addSentNotifications(Notification $sentNotifications): static
{
if (!$this->sentNotifications->contains($sentNotifications)) {
$this->sentNotifications->add($sentNotifications);
$sentNotifications->setUserWhoFiredEvent($this);
}
return $this;
}
public function removeSentNotifications(Notification $sentNotifications): static
{
if ($this->sentNotifications->removeElement($sentNotifications)) {
// set the owning side to null (unless already changed)
if ($sentNotifications->getUserWhoFiredEvent() === $this) {
$sentNotifications->setUserWhoFiredEvent(null);
}
}
return $this;
}
/**
* @return Collection<int, CustomRole>
*/
public function getCustomRoles(): Collection
{
return $this->customRoles;
}
public function addCustomRole(CustomRole $customRole): static
{
if (!$this->customRoles->contains($customRole)) {
$this->customRoles->add($customRole);
$customRole->setUser($this);
}
return $this;
}
public function removeCustomRole(CustomRole $customRole): static
{
if ($this->customRoles->removeElement($customRole)) {
// set the owning side to null (unless already changed)
if ($customRole->getUser() === $this) {
$customRole->setUser(null);
}
}
return $this;
}
/**
* @return Collection<int, Notification>
*/
public function getReceivedNotifications(): Collection
{
return $this->receivedNotifications;
}
public function addReceivedNotification(Notification $receivedNotification): static
{
if (!$this->receivedNotifications->contains($receivedNotification)) {
$this->receivedNotifications->add($receivedNotification);
$receivedNotification->setUserToNotify($this);
}
return $this;
}
public function removeReceivedNotification(Notification $receivedNotification): static
{
if ($this->receivedNotifications->removeElement($receivedNotification)) {
// set the owning side to null (unless already changed)
if ($receivedNotification->getUserToNotify() === $this) {
$receivedNotification->setUserToNotify(null);
}
}
return $this;
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace DMD\LaLigaApi\Enum;
enum NotificationType
{
case NEW_JOIN_LEAGUE_REQUEST;
case DECLINED_JOIN_LEAGUE_REQUEST;
case NEW_JOIN_TEAM_REQUEST;
case NEW_CAPTAIN_REQUEST;
case DECLINED_CAPTAIN_REQUEST;
case ACCEPTED_CAPTAIN_REQUEST;
public function getMessage(?string $requestingUserFullName, string $entityName): string
{
return match ($this){
self::NEW_JOIN_LEAGUE_REQUEST, self::NEW_JOIN_TEAM_REQUEST => "$requestingUserFullName , quiere unirse a $entityName.",
self::NEW_CAPTAIN_REQUEST => "$requestingUserFullName quiere ser capitán del equipo $entityName.",
self::DECLINED_JOIN_LEAGUE_REQUEST => "Han rechazado tu solicitud para unirte a la liga $entityName.",
self::DECLINED_CAPTAIN_REQUEST => "Han rechazado tu solicitud para ser capitán del equipo $entityName.",
self::ACCEPTED_CAPTAIN_REQUEST => "Han aceptado tu solicitud para ser capitán del equipo $entityName."
};
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace DMD\LaLigaApi\Enum;
enum Role: string
{
case LEAGUE_PRESIDENT = '_LEAGUE_PRESIDENT';
case TEAM_CAPTAIN = '_TEAM_CAPTAIN';
case LEAGUE_MEMBER = '_LEAGUE_MEMBER';
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace DMD\LaLigaApi\Exception;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Exception\ORMException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use DMD\LaLigaApi\Entity\Log;
class ExceptionListener
{
public function __construct(public EntityManagerInterface $entityManager){}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$log = new Log();
$log->setPayload($event->getRequest()->getContent());
if ($exception instanceof HttpExceptionInterface)
{
$log->setCode($exception->getStatusCode());
$log->setMessage($exception->getMessage());
$response = new JsonResponse([
'error'=> [
'code' => $exception->getStatusCode(),
'message' => $exception->getMessage()
]
]);
$response->headers->set('Content-Type', 'application/json');
$response->setStatusCode($exception->getStatusCode());
}
elseif($exception instanceof ValidationException)
{
$response = new JsonResponse(
data: [
'success' => false,
'validationErrors' => $exception->getValidationErrors()
],
status: $exception->getCode()
);
}
else
{
$log->setCode(Response::HTTP_INTERNAL_SERVER_ERROR);
$log->setMessage($exception->getMessage());
$response = new JsonResponse([
'error'=> [
'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
'message' => $exception->getMessage()
]
]);
$response->headers->set('Content-Type', 'application/json');
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
if (!($exception instanceof ORMException))
{
$this->entityManager->persist($log);
$this->entityManager->flush();
$this->entityManager->clear();
}
$event->setResponse($response);
$event->allowCustomResponseCode();
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace DMD\LaLigaApi\Exception;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
class ValidationException extends \Exception
{
public function __construct(
private readonly array $validationErrors,
string $message = "",
int $code = Response::HTTP_BAD_REQUEST,
?Throwable $previous = null,
)
{
parent::__construct($message, $code, $previous);
}
public function getValidationErrors(): array
{
return $this->validationErrors;
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace DMD\LaLigaApi;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
}
View File
+61
View File
@@ -0,0 +1,61 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\CustomRole;
use DMD\LaLigaApi\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<CustomRole>
*
* @method CustomRole|null find($id, $lockMode = null, $lockVersion = null)
* @method CustomRole|null findOneBy(array $criteria, array $orderBy = null)
* @method CustomRole[] findAll()
* @method CustomRole[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class CustomRoleRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, CustomRole::class);
}
public function findUserByRoleName(string $roleName): User
{
return $this->createQueryBuilder('r')
->select('u')
->join('r.user', 'u')
->where('r.name = :roleName')
->setParameter('roleName', $roleName)
->setMaxResults(1)
->getQuery()
->getResult();
}
// /**
// * @return CustomRole[] Returns an array of CustomRole objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('c')
// ->andWhere('c.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('c.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?CustomRole
// {
// return $this->createQueryBuilder('c')
// ->andWhere('c.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\Facility;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Facility>
*
* @method Facility|null find($id, $lockMode = null, $lockVersion = null)
* @method Facility|null findOneBy(array $criteria, array $orderBy = null)
* @method Facility[] findAll()
* @method Facility[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class FacilityRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Facility::class);
}
// /**
// * @return Facility[] Returns an array of Facility objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('f')
// ->andWhere('f.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('f.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Facility
// {
// return $this->createQueryBuilder('f')
// ->andWhere('f.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\File;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<File>
*
* @method File|null find($id, $lockMode = null, $lockVersion = null)
* @method File|null findOneBy(array $criteria, array $orderBy = null)
* @method File[] findAll()
* @method File[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class FileRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, File::class);
}
// /**
// * @return File[] Returns an array of File objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('f')
// ->andWhere('f.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('f.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?File
// {
// return $this->createQueryBuilder('f')
// ->andWhere('f.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\Game;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Game>
*
* @method Game|null find($id, $lockMode = null, $lockVersion = null)
* @method Game|null findOneBy(array $criteria, array $orderBy = null)
* @method Game[] findAll()
* @method Game[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class GameRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Game::class);
}
// /**
// * @return Game[] Returns an array of Game objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('g')
// ->andWhere('g.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('g.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Game
// {
// return $this->createQueryBuilder('g')
// ->andWhere('g.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\League;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<League>
*
* @method League|null find($id, $lockMode = null, $lockVersion = null)
* @method League|null findOneBy(array $criteria, array $orderBy = null)
* @method League[] findAll()
* @method League[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class LeagueRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, League::class);
}
// /**
// * @return League[] Returns an array of League objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('l')
// ->andWhere('l.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('l.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?League
// {
// return $this->createQueryBuilder('l')
// ->andWhere('l.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\Log;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Log>
*
* @method Log|null find($id, $lockMode = null, $lockVersion = null)
* @method Log|null findOneBy(array $criteria, array $orderBy = null)
* @method Log[] findAll()
* @method Log[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class LogRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Log::class);
}
// /**
// * @return Log[] Returns an array of Log objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('l')
// ->andWhere('l.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('l.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Log
// {
// return $this->createQueryBuilder('l')
// ->andWhere('l.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\Notification;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Notification>
*
* @method Notification|null find($id, $lockMode = null, $lockVersion = null)
* @method Notification|null findOneBy(array $criteria, array $orderBy = null)
* @method Notification[] findAll()
* @method Notification[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class NotificationRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Notification::class);
}
// /**
// * @return Notification[] Returns an array of Notification objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('n')
// ->andWhere('n.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('n.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Notification
// {
// return $this->createQueryBuilder('n')
// ->andWhere('n.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\Player;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Player>
*
* @method Player|null find($id, $lockMode = null, $lockVersion = null)
* @method Player|null findOneBy(array $criteria, array $orderBy = null)
* @method Player[] findAll()
* @method Player[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class PlayerRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Player::class);
}
// /**
// * @return Player[] Returns an array of Player objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('p')
// ->andWhere('p.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('p.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Player
// {
// return $this->createQueryBuilder('p')
// ->andWhere('p.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\SeasonData;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<SeasonData>
*
* @method SeasonData|null find($id, $lockMode = null, $lockVersion = null)
* @method SeasonData|null findOneBy(array $criteria, array $orderBy = null)
* @method SeasonData[] findAll()
* @method SeasonData[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class SeasonDataRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, SeasonData::class);
}
// /**
// * @return SeasonData[] Returns an array of SeasonData objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('s')
// ->andWhere('s.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('s.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?SeasonData
// {
// return $this->createQueryBuilder('s')
// ->andWhere('s.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\Season;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Season>
*
* @method Season|null find($id, $lockMode = null, $lockVersion = null)
* @method Season|null findOneBy(array $criteria, array $orderBy = null)
* @method Season[] findAll()
* @method Season[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class SeasonRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Season::class);
}
// /**
// * @return Season[] Returns an array of Season objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('s')
// ->andWhere('s.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('s.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Season
// {
// return $this->createQueryBuilder('s')
// ->andWhere('s.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\Team;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Team>
*
* @method Team|null find($id, $lockMode = null, $lockVersion = null)
* @method Team|null findOneBy(array $criteria, array $orderBy = null)
* @method Team[] findAll()
* @method Team[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class TeamRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Team::class);
}
// /**
// * @return Team[] Returns an array of Team objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('t')
// ->andWhere('t.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('t.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Team
// {
// return $this->createQueryBuilder('t')
// ->andWhere('t.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace DMD\LaLigaApi\Repository;
use DMD\LaLigaApi\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
/**
* @extends ServiceEntityRepository<User>
*
* @implements PasswordUpgraderInterface<User>
*
* @method User|null find($id, $lockMode = null, $lockVersion = null)
* @method User|null findOneBy(array $criteria, array $orderBy = null)
* @method User[] findAll()
* @method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
{
if (!$user instanceof User) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class));
}
$user->setPassword($newHashedPassword);
$this->getEntityManager()->persist($user);
$this->getEntityManager()->flush();
}
/**
* @return User[] Returns an array of User objects
*/
public function findByCustomRole(string $roleName): array
{
return $this->createQueryBuilder('u')
->innerJoin('u.customRoles', 'r')
->where('r.r.name = :roleName')
->setParameter('roleName', $roleName)
->getQuery()
->getResult()
;
}
// public function findOneBySomeField($value): ?User
// {
// return $this->createQueryBuilder('u')
// ->andWhere('u.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace DMD\LaLigaApi\Service\Common;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Enum\Role;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\LeagueRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class AuthorizeRequest
{
public function __construct(
public Security $security,
public CustomRoleRepository $customRoleRepository,
public LeagueRepository $leagueRepository
)
{}
public function authorizeLeaguePresident(int $leagueId): void
{
$userEntity = $this->security->getUser();
if (is_null($userEntity))
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Unauthorized.");
}
$customRole = $this->customRoleRepository->findBy([
'name' => $leagueId . Role::LEAGUE_PRESIDENT->value,
'userEntity' => $userEntity
]);
if (is_null($customRole))
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Usuario no tiene permiso para editar la liga.");
}
}
public function teamCaptainRequest(int $leagueId, $teamId): User
{
$userEntity = $this->security->getUser();
if (!$userEntity instanceof User)
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Unauthorized");
}
$captainCustomRole = $this->customRoleRepository->findBy([
'name' => $teamId . Role::TEAM_CAPTAIN->value,
]);
if (!is_null($captainCustomRole))
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Equipo con id: $teamId ya tiene capitan");
}
$leagueMemberRole = $this->customRoleRepository->findBy([
'name' => $leagueId . Role::LEAGUE_MEMBER->value,
'user' => $userEntity
]);
if (is_null($leagueMemberRole))
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Usuario no es miembro de la liga");
}
return $userEntity;
}
public function isLeaguePresident(int $leagueId, User $leagueAdmin): bool
{
$adminRoles = $leagueAdmin->getCustomRoles();
if (!$adminRoles->isEmpty())
{
foreach ($adminRoles as $adminRoleEntity)
{
$explodedRole = explode('_', $adminRoleEntity->getName());
if (
strtolower($explodedRole[1]) == 'league' &&
strtolower($explodedRole[2]) == 'president' &&
$explodedRole[0] == $leagueId
)
{
return true;
}
}
}
throw new HttpException(Response::HTTP_NOT_FOUND,'Forbidden.');
}
}
+112
View File
@@ -0,0 +1,112 @@
<?php
namespace DMD\LaLigaApi\Service\Common;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\Team;
use DMD\LaLigaApi\Entity\User;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
class EmailSender
{
public function __construct(
public MailerInterface $mailer
)
{
}
/**
* @throws TransportExceptionInterface
*/
public function newJoinLeagueRequest(User $leagueAdminEntity, User $requestingUserEntity, League $leagueEntity): void
{
$requestingUserFullName = $requestingUserEntity->getFirstName() . ' '. $requestingUserEntity->getLastName();
$email = (new TemplatedEmail())
->from('soporteliga@dyb-tech.com')
->to(
(new Address($leagueAdminEntity?->getEmail()))
)
->subject("Nueva solicitud: $requestingUserFullName se quiere unir a ". $leagueEntity->getName())
->htmlTemplate('joinLeague.html.twig')
->context([
'user' => $requestingUserEntity,
'president'=> $leagueAdminEntity,
'league' => $leagueEntity
]);
$this->mailer->send($email);
}
/**
* @throws TransportExceptionInterface
*/
public function teamCaptainRequest(Team $teamEntity, User $leagueAdminEntity, User $requestingUser, League $leagueEntity): void
{
$requestingUserFullName = $requestingUser->getFirstName() .' '. $requestingUser->getLastName();
$email = (new TemplatedEmail())
->from('soporteliga@dyb-tech.com')
->to(
(new Address($leagueAdminEntity->getEmail()))
)
->subject("Nueva solicitud: $requestingUserFullName se quiere unir a ". $leagueEntity->getName())
->htmlTemplate('teamCaptainRequest.html.twig')
->context([
'userToNotify' => $leagueAdminEntity,
'requestingUser'=> $requestingUser,
'league'=> $leagueEntity,
'team' => $teamEntity
]);
$this->mailer->send($email);
}
/**
* @throws TransportExceptionInterface
*/
public function declineTeamCaptainRequest(User $rejectedUser, League $leagueEntity): void
{
$email = (new TemplatedEmail())
->from('soporte@leagueranks.es')
->to((new Address($rejectedUser->getEmail())))
->subject('Tu solicitud ha sido rechazada.')
->htmlTemplate('declinedRequest.html.twig')
->context([
'rejectedUserEntity' => $rejectedUser,
'leagueEntity'=> $leagueEntity
]);
$this->mailer->send($email);
}
/**
* @throws TransportExceptionInterface
*/
public function joinLeagueRequestAccepted(User $user, League $league): void
{
$email = (new TemplatedEmail())
->from('soporte@leagueranks.es')
->to((new Address($user->getEmail())))
->subject('Tu solicitud ha sido aceptada.')
->htmlTemplate('welcomeToLeague.html.twig')
->context([
'user' => $user,
'leagueName'=> $league->getName()
]);
$this->mailer->send($email);
}
/**
* @throws TransportExceptionInterface
*/
public function joinLeagueRequestDeclined(User $user, League $league): void
{
$email = (new TemplatedEmail())
->from('soporte@leagueranks.es')
->to((new Address($user->getEmail())))
->subject('Tu solicitud ha sido rechazada.')
->htmlTemplate('leagueRequestDeclined.html.twig')
->context([
'user' => $user,
'leagueName'=> $league->getName()
]);
$this->mailer->send($email);
}
}
@@ -0,0 +1,96 @@
<?php
namespace DMD\LaLigaApi\Service\Common;
use DMD\LaLigaApi\Dto\NotificationDto;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\Notification;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Enum\NotificationType;
use DMD\LaLigaApi\Enum\Role;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\TeamRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
class NotificationFactory
{
public function __construct(
public CustomRoleRepository $customRoleRepository,
public TeamRepository $teamRepository,
public EntityManagerInterface $entityManager,
public EmailSender $emailSender
)
{
}
/**
* @throws TransportExceptionInterface
*/
public function newJoinLeagueRequest(User $requestingUserEntity, League $leagueEntity, ?string $message): void
{
$leagueAdminEntity = $this->customRoleRepository->findUserByRoleName($leagueEntity->getId() . Role::LEAGUE_PRESIDENT->value);
if (is_null($leagueAdminEntity))
{
throw new HttpException(Response::HTTP_NOT_FOUND,'Presidente de liga con id' . $leagueEntity->getId() .' no ha sido encontrado');
}
$requestingUserFullName = $requestingUserEntity->getFirstName() . ' '. $requestingUserEntity->getLastName();
$notification = new Notification();
$notification->setUserWhoFiredEvent($requestingUserEntity);
$notification->setUserToNotify($leagueAdminEntity);
$notification->setType(NotificationType::NEW_JOIN_LEAGUE_REQUEST->name);
$notification->setMessage(
$message ?? NotificationType::NEW_JOIN_LEAGUE_REQUEST->getMessage(
$requestingUserFullName,
$leagueEntity->getName()
)
);
$notification->setLeague($leagueEntity);
$this->entityManager->persist($notification);
$this->entityManager->flush();
$this->emailSender->newJoinLeagueRequest($leagueAdminEntity, $requestingUserEntity, $leagueEntity);
}
public function teamCaptainRequest(User $requestingUser, User $leagueAdminEntity, string $message, League $leagueEntity, int $teamId): void
{
$teamEntity = $this->teamRepository->find($teamId);
if (is_null($teamEntity))
{
throw new HttpException(
Response::HTTP_NOT_FOUND,
"Equipo con ID $teamId no ha sido encontrado"
);
}
$requestingUserFullName = $requestingUser->getFirstName() .' '. $requestingUser->getLastName();
$notification = new Notification();
$notification->setUserWhoFiredEvent($requestingUser);
$notification->setUserToNotify($leagueAdminEntity);
$notification->setType(NotificationType::NEW_CAPTAIN_REQUEST->name);
$notification->setMessage($message ?? NotificationType::NEW_CAPTAIN_REQUEST->getMessage($requestingUserFullName, $teamEntity->getName()));
$notification->setTeamId($teamId);
$notification->setLeague($leagueEntity);
$notification->setIsRead(false);
$this->entityManager->persist($notification);
$this->entityManager->flush();
$this->emailSender->teamCaptainRequest($teamEntity, $leagueAdminEntity, $requestingUser, $leagueEntity);
}
public function joinLeagueRequestDeclined(User $rejectedUser, League $leagueEntity): void
{
$notification = new Notification();
$notification->setUserToNotify($rejectedUser);
$notification->setType(NotificationType::DECLINED_CAPTAIN_REQUEST->name);
$notification->setMessage(
NotificationType::DECLINED_JOIN_LEAGUE_REQUEST->getMessage(
requestingUserFullName: null,
entityName: $leagueEntity->getName()
)
);
$notification->setIsRead(false);
$this->entityManager->persist($notification);
$this->entityManager->flush();
$this->emailSender->joinLeagueRequestDeclined($rejectedUser, $leagueEntity);
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace DMD\LaLigaApi\Service\Common;
use DMD\LaLigaApi\Dto\TeamDto;
use DMD\LaLigaApi\Entity\Team;
class TeamFactory
{
public static function create(TeamDto $teamDto): Team
{
$teamEntity = new Team();
if (!empty($teamDto->name))
{
$teamEntity->setName($teamDto->name);
}
$teamEntity->setActive(true);
return $teamEntity;
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace DMD\LaLigaApi\Service\League;
use DMD\LaLigaApi\Dto\LeagueDto;
use DMD\LaLigaApi\Entity\League;
class LeagueFactory
{
public static function create(LeagueDto $leagueDto): League
{
$leagueEntity = new League();
if (!empty($leagueDto->name))
{
$leagueEntity->setName($leagueDto->name);
}
if (!empty($leagueDto->logo))
{
$leagueEntity->setLogo($leagueDto->logo);
}
if (!empty($leagueDto->description))
{
$leagueEntity->setDescription($leagueDto->description);
}
if (isset($leagueDto->pointsPerWin))
{
$leagueEntity->setPointsPerWin($leagueDto->pointsPerWin);
}
if (!empty($leagueDto->pointsPerDraw))
{
$leagueEntity->setPointsPerDraw($leagueDto->pointsPerDraw);
}
if (!empty($leagueDto->pointsPerLoss))
{
$leagueEntity->setPointsPerLoss($leagueDto->pointsPerLoss);
}
if (!empty($leagueDto->matchesBetweenTeams))
{
$leagueEntity->setMatchesBetweenTeams($leagueDto->matchesBetweenTeams);
}
if (!empty($leagueDto->blockedMatchDates))
{
$leagueEntity->setBlockedMatchDates($leagueDto->blockedMatchDates);
}
if (!empty($leagueDto->city))
{
$leagueEntity->setCity($leagueDto->city);
}
$leagueEntity->setActive(true);
return $leagueEntity;
}
}
@@ -0,0 +1,74 @@
<?php
namespace DMD\LaLigaApi\Service\League\acceptJoinLeagueRequest;
use DMD\LaLigaApi\Entity\CustomRole;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Enum\Role;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\TeamRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\EmailSender;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
class HandleAcceptJoinLeagueRequest
{
public function __construct(
public EntityManagerInterface $entityManager,
public Security $security,
public AuthorizeRequest $authorizeRequest,
public UserRepository $userRepository,
public LeagueRepository $leagueRepository,
public TeamRepository $teamRepository,
public EmailSender $emailSender
){}
/**
* @throws TransportExceptionInterface
*/
public function __invoke(Request $request, int $leagueId, int $userId): JsonResponse
{
$leagueAdminEntity = $this->security->getUser();
if (!$leagueAdminEntity instanceof User)
{
throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Internal Server Error');
}
$this->authorizeRequest->isLeaguePresident($leagueId, $leagueAdminEntity);
$leagueEntity = $this->leagueRepository->find($leagueId);
if (is_null($leagueEntity))
{
throw new HttpException(Response::HTTP_NOT_FOUND, "Liga con id $leagueId no ha sido encontrada");
}
$requestingUserEntity = $this->userRepository->find($userId);
if (is_null($requestingUserEntity))
{
throw new HttpException(Response::HTTP_NOT_FOUND,"El usuario con id: $userId no ha sido encontrado.");
}
$customRoleEntity = new CustomRole();
$customRoleEntity->setName($leagueId. Role::LEAGUE_MEMBER->value);
$customRoleEntity->setUser($requestingUserEntity);
$this->entityManager->persist($customRoleEntity);
$this->entityManager->flush();
$this->emailSender->joinLeagueRequestAccepted(
$requestingUserEntity,
$leagueEntity
);
return new JsonResponse(
data: [
'success' => true,
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,69 @@
<?php
namespace DMD\LaLigaApi\Service\League\createLeague;
use DMD\LaLigaApi\Dto\LeagueDto;
use DMD\LaLigaApi\Entity\CustomRole;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Enum\Role;
use DMD\LaLigaApi\Exception\ValidationException;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\League\LeagueFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HandleCreateLeague
{
public function __construct(
public LeagueFactory $leagueFactory,
public EntityManagerInterface $entityManager,
public Security $security,
public UserRepository $userRepository
){}
/**
* @throws ValidationException
*/
public function __invoke(Request $request): JsonResponse
{
$userEntity = $this->userRepository->findOneBy([
'email' => $this->security->getUser()?->getUserIdentifier()
]);
if (is_null($userEntity))
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Unauthorized.");
}
$leagueDto = new LeagueDto();
$leagueDto->fillFromArray($request->toArray());
$leagueDto->validate();
$leagueEntity = $this->leagueFactory::create($leagueDto);
$leagueEntity->setActive(true);
$this->assignPresidentRole($leagueEntity->getId(), $userEntity);
$this->entityManager->persist($leagueEntity);
$this->entityManager->flush();
$leagueDto->id = $leagueEntity->getId();
$leagueDto->createdAt = $leagueEntity->getCreatedAt();
return new JsonResponse(
data: [
'success' => true,
'league' => $leagueDto->toArray()
],
status: Response::HTTP_OK
);
}
public function assignPresidentRole(int $leagueId, User $userEntity): void
{
$leaguePresidentRole = new CustomRole();
$leaguePresidentRole->setName($leagueId. Role::LEAGUE_PRESIDENT->value);
$leaguePresidentRole->setUser($userEntity);
$this->entityManager->persist($leaguePresidentRole);
}
}
@@ -0,0 +1,62 @@
<?php
namespace DMD\LaLigaApi\Service\League\declineJoinLeagueRequest;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\NotificationFactory;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
class HandleDeclineJoinLeagueRequest
{
public function __construct(
public Security $security,
public UserRepository $userRepository,
public LeagueRepository $leagueRepository,
public AuthorizeRequest $authorizeRequest,
public NotificationFactory $notificationFactory
){}
/**
* @throws TransportExceptionInterface
*/
public function __invoke(
Request $request,
int $leagueId,
int $rejectedUserId
): JsonResponse
{
$leagueAdmin = $request->getUser();
if (!$leagueAdmin instanceof User)
{
throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Internal Server Error');
}
$this->authorizeRequest->isLeaguePresident($leagueId, $leagueAdmin);
$leagueEntity = $this->leagueRepository->find($leagueId);
if (is_null($leagueEntity))
{
throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, "Liga con id: $leagueId no ha sido encontrada");
}
$rejectedUser = $this->userRepository->find($rejectedUserId);
if (is_null($rejectedUser))
{
throw new HttpException(Response::HTTP_NOT_FOUND, "El usuario con id $rejectedUserId no ha sido encontrado.");
}
$this->notificationFactory->joinLeagueRequestDeclined($rejectedUser, $leagueEntity);
return new JsonResponse(
data: [
'success' => true,
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,48 @@
<?php
namespace DMD\LaLigaApi\Service\League\getAllLeagues;
use DMD\LaLigaApi\Dto\LeagueDto;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Service\League\getLeagueById\HandleGetLeagueById;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HandleGetAllLeagues
{
private static int $PAGE_SIZE = 100;
public function __construct(
public LeagueRepository $leagueRepository
){}
public function __invoke(): JsonResponse
{
$page = 1;
$leagueCollection = $this->leagueRepository->findBy([
'active' => true
],
limit: self::$PAGE_SIZE,
offset: ($page * self::$PAGE_SIZE) - self::$PAGE_SIZE
);
$leagueArray = [];
if (!is_null($leagueCollection))
{
foreach ($leagueCollection as $leagueObj)
{
$leagueDto = new LeagueDto();
$leagueDto->fillFromObject($leagueObj);
$leagueArray[] = $leagueDto->toArray();
}
}
return new JsonResponse(
data: [
'success' => true,
'leagues' => $leagueArray
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,38 @@
<?php
namespace DMD\LaLigaApi\Service\League\getLeagueById;
use DMD\LaLigaApi\Dto\LeagueDto;
use DMD\LaLigaApi\Repository\LeagueRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HandleGetLeagueById
{
public function __construct(
public LeagueRepository $leagueRepository,
){}
public function __invoke(Request $request, int $leagueId): JsonResponse
{
$leagueEntity = $this->leagueRepository->find($leagueId);
if (is_null($leagueEntity))
{
throw new HttpException(
Response::HTTP_NOT_FOUND,
"Liga no encontrada"
);
}
$leagueDto = new LeagueDto();
$leagueDto->fillFromObject($leagueEntity);
return new JsonResponse(
data: [
'success' => true,
'league' => $leagueDto->toArray()
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,64 @@
<?php
namespace DMD\LaLigaApi\Service\League\joinTeam;
use DMD\LaLigaApi\Enum\Role;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\TeamRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\NotificationFactory;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HandleCaptainRequest
{
public function __construct(
public AuthorizeRequest $authorizeRequest,
public CustomRoleRepository $customRoleRepository,
public LeagueRepository $leagueRepository,
public TeamRepository $teamRepository,
public NotificationFactory $notificationFactory
){}
public function __invoke(
Request $request,
int $leagueId,
int $teamId
): JsonResponse
{
$leagueToJoinEntity = $this->leagueRepository->find($leagueId);
if (is_null($leagueToJoinEntity))
{
throw new HttpException(Response::HTTP_NOT_FOUND, "Liga con id: $leagueId no ha sido encontrada");
}
$requestingUserEntity = $this->authorizeRequest->teamCaptainRequest($leagueId, $teamId);
$userToNotifyEntity = $this->customRoleRepository->findUserByRoleName($leagueId . Role::LEAGUE_PRESIDENT->value);
if (is_null($userToNotifyEntity))
{
throw new HttpException(Response::HTTP_NOT_FOUND, "No se ha encontrado presidente de la liga con id $leagueId");
}
$teamToJoinEntity = $this->teamRepository->find($teamId);
if (is_null($teamToJoinEntity))
{
throw new HttpException(Response::HTTP_NOT_FOUND, 'Equipo no encontrado.');
}
$this->notificationFactory->teamCaptainRequest(
$requestingUserEntity,
$userToNotifyEntity,
$request->toArray()['message'],
$leagueToJoinEntity,
$teamId
);
return new JsonResponse(
data: [
'success' => true,
'message' => 'La solicitud ha sido enviada correctamente.'
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,71 @@
<?php
namespace DMD\LaLigaApi\Service\League\newJoinLeagueRequest;
use DMD\LaLigaApi\Dto\NotificationDto;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\Notification;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\TeamRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\Common\NotificationFactory;
use DMD\LaLigaApi\Service\League\LeagueFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
class HandleNewJoinLeagueRequest
{
public function __construct(
public Security $security,
public LeagueRepository $leagueRepository,
public NotificationFactory $notificationFactory,
public MailerInterface $mailer
){}
/**
* @throws TransportExceptionInterface
*/
public function __invoke(
Request $request,
int $leagueId
): JsonResponse
{
$requestingUser = $this->security->getUser();
if (!($requestingUser instanceof User))
{
throw new HttpException(
Response::HTTP_FORBIDDEN,
"Unauthorized.");
}
$leagueToJoin = $this->leagueRepository->find($leagueId);
if (is_null($leagueToJoin))
{
throw new HttpException(
Response::HTTP_NOT_FOUND,
'Liga no encontrada.');
}
$this->notificationFactory->newJoinLeagueRequest(
$requestingUser,
$leagueToJoin,
($request->toArray())['message'] ?? null
);
return new JsonResponse(
data: [
'success' => true,
'message' => 'La solicitud ha sido enviada correctamente.'
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,87 @@
<?php
namespace DMD\LaLigaApi\Service\League\updateLeague;
use DMD\LaLigaApi\Dto\LeagueDto;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\League\LeagueFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HandleUpdateLeague
{
public function __construct(
public LeagueFactory $leagueSaver,
public EntityManagerInterface $entityManager,
public Security $security,
public UserRepository $userRepository,
public LeagueRepository $leagueRepository,
public CustomRoleRepository $customRoleRepository,
){}
public function __invoke(Request $request, int $leagueId): JsonResponse
{
$authorizationResult = $this->checkUserAuthorization($leagueId);
$leagueDto = new LeagueDto();
$leagueDto->fillFromObject($authorizationResult['leagueObj']);
$leagueDto->fillFromArray($request->toArray());
$leagueDto->validate();
if (!empty($leagueDto->validationErrors))
{
return $this->generateErrorResponse($leagueDto->validationErrors);
}
$this->leagueSaver->save($authorizationResult['leagueObj'], $leagueDto);
$this->entityManager->flush();
return new JsonResponse(
data: [
'success' => true,
'league' => $leagueDto->toArray()
],
status: Response::HTTP_OK
);
}
public function generateErrorResponse(array $validationErrors): JsonResponse
{
return new JsonResponse(
data: [
'success' => false,
'error' => $validationErrors
],
status: Response::HTTP_OK
);
}
public function checkUserAuthorization(int $leagueId): array
{
$user = $this->security->getUser();
if (is_null($user))
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Unauthorized.");
}
$customRole = $this->customRoleRepository->findBy([
'name' => $leagueId.'_LEAGUE_PRESIDENT',
'user' => $user
]);
if (is_null($customRole))
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Usuario no tiene permiso para editar la liga.");
}
$leagueObj = $this->leagueRepository->find($leagueId);
if (is_null($leagueObj))
{
throw new HttpException(Response::HTTP_NOT_FOUND, "Liga con id: ". $leagueId .' no ha sido encontrada.');
}
return [
'leagueObj' => $leagueObj,
'userObj' => $user
];
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace DMD\LaLigaApi\Service\Season;
use DMD\LaLigaApi\Dto\SeasonDto;
use DMD\LaLigaApi\Entity\Season;
class SeasonFactory
{
public static function create(SeasonDto $seasonDto): Season
{
$seasonEntity = new Season();
$seasonEntity->setActive(true);
if (!empty($seasonDto->dateStart))
{
$seasonEntity->setDateStart($seasonDto->dateStart);
}
return $seasonEntity;
}
}
@@ -0,0 +1,60 @@
<?php
namespace DMD\LaLigaApi\Service\Season\addTeam;
use DMD\LaLigaApi\Dto\TeamDto;
use DMD\LaLigaApi\Exception\ValidationException;
use DMD\LaLigaApi\Repository\SeasonRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\TeamFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HandleAddTeam
{
public function __construct(
public AuthorizeRequest $authorizeRequest,
public TeamFactory $teamFactory,
public EntityManagerInterface $entityManager,
public SeasonRepository $seasonRepository
){}
/**
* @throws ValidationException
*/
public function __invoke(
Request $request,
int $leagueId,
int $seasonId
): JsonResponse
{
$this->authorizeRequest->authorizeLeaguePresident($leagueId);
$seasonEntity = $this->seasonRepository->find($seasonId);
if (is_null($seasonEntity))
{
throw new HttpException(
Response::HTTP_NOT_FOUND,
'Temporada con ID: '. $seasonId .' no ha sido encontrada.'
);
}
$teamDto = new TeamDto();
$teamDto->fillFromArray($request->toArray());
$teamDto->validate();
$teamEntity = $this->teamFactory::create($teamDto);
$teamEntity->addSeason($seasonEntity);
$this->entityManager->persist($teamEntity);
$this->entityManager->flush();
$teamDto->id = $teamEntity->getId();
return new JsonResponse(
data: [
'success' => true,
'team' => $teamDto->toArray()
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,260 @@
<?php
namespace DMD\LaLigaApi\Service\Season\createGameCalendar;
use DMD\LaLigaApi\Dto\GameDto;
use DMD\LaLigaApi\Dto\TeamDto;
use DMD\LaLigaApi\Entity\Game;
use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\Season;
use DMD\LaLigaApi\Entity\Team;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Exception\ValidationException;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\SeasonRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\User\UserInterface;
class HandleCreateGameCalendarRequest
{
public function __construct(
public AuthorizeRequest $authorizeRequest,
public Security $security,
public LeagueRepository $leagueRepository,
public SeasonRepository $seasonRepository
)
{
}
/**
* @throws ValidationException
* @throws \Exception
*/
public function __invoke(Request $request, int $leagueId, int $seasonId): JsonResponse
{
$this->authorizeRequest->authorizeLeaguePresident($leagueId);
$leaguePresidentEntity = $this->security->getUser();
$leagueEntity = $this->leagueRepository->find($leagueId);
$seasonEntity = $this->seasonRepository->findOneBy([
'active' => true,
'id' => $seasonId,
'league' => $leagueEntity
]);
$this->validateEntities($leaguePresidentEntity, $leagueEntity, $leagueId, $seasonEntity);
$teamEntityList = ($seasonEntity->getTeams())->toArray();
$requestArray = $request->toArray();
$numberOfTeams = count($teamEntityList);
$numberOfWeeks = (2 * ($numberOfTeams * ($numberOfTeams - 1))) / $requestArray['gamesPerWeek'];
$fromDate = new \DateTime($requestArray['fromDate'], new \DateTimeZone('Europe/Madrid'));
$fromDate = match($fromDate->format('l')){
'Saturday', 'Sunday' => $fromDate->modify('next monday'),
default => $fromDate
};
$totalWeeks = $this->weeksBetweenTwoDates(
new \DateTime($request->toArray()['fromDate'], new \DateTimeZone('Europe/Madrid')),
new \DateTime($request->toArray()['toDate'], new \DateTimeZone('Europe/Madrid'))
);
$currentWeek = 1;
$currentGame = 1;
$totalGames = (count($teamEntityList) * ((count($teamEntityList) - 1)) / 2) * ($request->toArray()['gamesBetweenTeams'] ?? 2); //todo con esto puedes validar si el rango de fecha es suficiente para que se jueguen todos los juegos
$calendarInWeeks = [];
$gameDtoList = [];
$firstDayOfWeek = new \DateTime($request->toArray()['fromDate']);
$lastDayOfWeek = (clone $firstDayOfWeek)->modify('+7 days'); //todo forzar o dar la opcion de que la semana siguiente empiece el lunes
while ($currentWeek <= $totalWeeks)
{
$gamesForCurrentWeekList = [];
for ($i = 0; $i < $request->toArray()['gamesPerWeek']; $i++)
{
$gameEntity = $this->generateCalendar(
$teamEntityList->toArray(),
$currentGame,
$request->toArray()['unavailableLeagueDays'],
$request->toArray()['specificDatesNotAvailable']
);
$gamesForCurrentWeekList[] = $gameEntity;
$currentGame++;
}
$calendar[$currentWeek] = $gamesForCurrentWeekList;
$currentWeek++;
}
foreach ($calendar as $gamesForWeekList)
{
foreach ($gamesForWeekList as $gameEntity)
{
$gameDto = new GameDto();
$gameDto->fillFromObject($gameEntity);
$gameDtoList[] = $gameDto->toArray();
}
}
return new JsonResponse([
'success' => true,
'games' => $gameDtoList
]);
}
public function validateEntities(?UserInterface $leaguePresidentEntity, ?League $leagueEntity, int $leagueId, ?Season $seasonEntity): void
{
if (!($leaguePresidentEntity instanceof User))
{
throw new HttpException(Response::HTTP_UNAUTHORIZED, 'Forbidden');
}
if (!($leagueEntity instanceof League))
{
throw new HttpException(Response::HTTP_UNAUTHORIZED, "Liga con ID $leagueId no ha sido encontrada");
}
if (!($seasonEntity instanceof Season))
{
throw new HttpException(Response::HTTP_UNAUTHORIZED, "La liga no tiene temporadas activas");
}
}
/**
* @throws ValidationException
*/
public function weeksBetweenTwoDates(\DateTime $fromDate, \DateTime $toDate): float
{
if ($fromDate > $toDate)
{
$toDateString = $toDate->format('Y-m-d');
$fromDateString = $fromDate->format('Y-m-d');
throw new ValidationException(["$toDateString no puede ser anterior a $fromDateString"]);
}
return floor($fromDate->diff($toDate)->days/7);
}
public function generateCalendar(array $teamEntityArray, array $daysNotAvailable, array $specificDatesNotAvailable, int $totalGames): Game
{
$gameDtoList = [];
//generar los posibles juegos
/**
* @var Team $awayTeamEntity
* @var Team $homeTeamEntity
*/
foreach ($teamEntityArray as $homeTeamEntity)
{
foreach ($teamEntityArray as $awayTeamEntity)
{
if ($homeTeamEntity->getId() !== $awayTeamEntity->getId())
{
$gameDtoList[$homeTeamEntity->getName().':'. $awayTeamEntity->getName()] = $this->createGameDto(
homeTeamEntity: $homeTeamEntity,
awayTeamEntity: $awayTeamEntity
);
$gameDtoList[$awayTeamEntity->getName().':'. $homeTeamEntity->getName()] = $this->createGameDto(
homeTeamEntity: $awayTeamEntity,
awayTeamEntity: $homeTeamEntity
);
if (count($gameDtoList) == $totalGames)
{
break;
}
}
}
}
//asumiendo que tengo un juego por semana por cada equipo y 3 juegos, dame todas las posibles fechas
//puedes tener un from date o tomas hoy de fecha de partida,
if (empty($requestArray['fromDate']))
{
$fromDate = new \DateTimeImmutable('now', new \DateTimeZone('Europe/Madrid'));
}
else
{
$fromDate = \DateTimeImmutable::createFromFormat('Y-m-d', $requestArray['fromDate'], new \DateTimeZone('Europe/Madrid'));
}
// $totalGames = count($gameDtoList);
// $totalWeeks = $totalGames/$requestArray['gamesPerWeek'];
// $toDate = $fromDate->modify("+$totalWeeks weeks");
// return $game;
}
private function createGameDto(Team $homeTeamEntity, Team $awayTeamEntity): GameDto
{
$gameDto = new GameDto();
$homeTeamDto = new TeamDto();
$homeTeamDto->fillFromObject($homeTeamEntity);
$gameDto->homeTeamDto = $homeTeamDto;
$awayTeamDto = new TeamDto();
$awayTeamDto->fillFromObject($awayTeamEntity);
$gameDto->awayTeamDto = $awayTeamDto;
return $gameDto;
}
private function generateWeeklyRanges($fromDate, $toDate)
{
$start = new \DateTime($fromDate);
$end = new \DateTime($toDate);
$ranges = [];
// If the start date is not a Monday, adjust it to the next Monday
if ($start->format('N') != 1) {
$start->modify('next Monday');
}
while ($start <= $end) {
$endOfWeek = clone $start;
$endOfWeek->modify('next Sunday');
// Ensure the end of the week does not exceed the end date
if ($endOfWeek > $end) {
$endOfWeek = clone $end;
}
$ranges[] = [
'start' => $start->format('Y-m-d'),
'end' => $endOfWeek->format('Y-m-d')
];
// Move to the next Monday
$start->modify('next Monday');
}
return $ranges;
}
function generatePossibleDates($games, $restrictions)
{
global $gamesByDate;
foreach ($games as $game) {
$team1 = $game[0];
$team2 = $game[1];
// Generate dates for the next 4 weeks
for ($week = 0; $week < 4; $week++) {
for ($day = 0; $day < 7; $day++) {
$date = new \DateTime();
$date->modify("+$week weeks");
$date->modify("+$day days");
// Check if the day is off for either team
if (in_array($date->format('l'), $restrictions['daysOff'])) {
continue;
}
// Check if the date is a specific date off for either team
if (in_array($date->format('Y-m-d'), $restrictions['specificDatesOff'])) {
continue;
}
// Check if the team has reached the maximum games per week
$dateStr = $date->format('Y-m-d');
if (isset($gamesByDate[$dateStr])) {
$gameCount = count($gamesByDate[$dateStr]);
if ($gameCount >= $restrictions['gamesPerWeek']) {
continue;
}
}
// Add the game to the list of possible dates for the date
$gamesByDate[$dateStr][] = [$team1, $team2];
}
}
}
}
}
@@ -0,0 +1,60 @@
<?php
namespace DMD\LaLigaApi\Service\Season\createSeason;
use DMD\LaLigaApi\Dto\SeasonDto;
use DMD\LaLigaApi\Exception\ValidationException;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\TeamFactory;
use DMD\LaLigaApi\Service\Season\SeasonFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class HandleCreateSeason
{
public function __construct(
public SeasonFactory $seasonFactory,
public TeamFactory $teamFactory,
public AuthorizeRequest $authorizeRequest,
public LeagueRepository $leagueRepository,
public EntityManagerInterface $entityManager,
){}
/**
* @throws ValidationException
*/
public function __invoke(Request $request, int $leagueId): JsonResponse
{
$this->authorizeRequest->authorizeLeaguePresident($leagueId);
$leagueEntity = $this->leagueRepository->find($leagueId);
$seasonDto = new SeasonDto();
$seasonDto->fillFromArray($request->toArray());
$seasonDto->validate();
$seasonEntity = $this->seasonFactory::create($seasonDto);
$seasonEntity->setLeague($leagueEntity);
if (!empty($seasonDto->teamDtoList))
{
foreach ($seasonDto->teamDtoList as $teamDto)
{
$teamEntity = $this->teamFactory::create($teamDto);
$this->entityManager->persist($teamEntity);
}
}
$this->entityManager->persist($seasonEntity);
$this->entityManager->flush();
$seasonDto->id = $seasonEntity->getId();
return new JsonResponse(
data: [
'success' => true,
'season' => $seasonDto->toArray()
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,47 @@
<?php
namespace DMD\LaLigaApi\Service\Season\getAllSeasons;
use DMD\LaLigaApi\Dto\SeasonDto;
use DMD\LaLigaApi\Repository\SeasonRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class HandleGetAllSeason
{
public const PAGE_SIZE = 10;
public function __construct(
public EntityManagerInterface $entityManager,
public SeasonRepository $seasonRepository,
){}
public function __invoke(Request $request, int $page): JsonResponse
{
$seasonCollection = $this->seasonRepository->findBy([
'active' => true
],
limit: 10,
offset: ($page * self::PAGE_SIZE) - self::PAGE_SIZE
);
$seasonArray = [];
if (!is_null($seasonCollection))
{
foreach ($seasonCollection as $seasonObj)
{
$seasonDto = new SeasonDto();
$seasonDto->fillFromObject($seasonObj);
$seasonArray[] = $seasonDto->toArray();
}
}
return new JsonResponse(
data: [
'success' => true,
'seasons' => $seasonArray
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,44 @@
<?php
namespace DMD\LaLigaApi\Service\Season\getSeasonById;
use DMD\LaLigaApi\Dto\LeagueDto;
use DMD\LaLigaApi\Dto\SeasonDto;
use DMD\LaLigaApi\Repository\SeasonRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\League\LeagueFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HandleGetSeasonById
{
public function __construct(
public EntityManagerInterface $entityManager,
public SeasonRepository $seasonRepository,
){}
public function __invoke(Request $request, int $seasonId): JsonResponse
{
$seasonObj = $this->seasonRepository->find($seasonId);
if (is_null($seasonObj))
{
throw new HttpException(
Response::HTTP_NOT_FOUND,
"Temporada no encontrada."
);
}
$seasonDto = new SeasonDto();
$seasonDto->fillFromObject($seasonObj);
return new JsonResponse(
data: [
'success' => true,
'season' => $seasonDto->toArray()
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,85 @@
<?php
namespace DMD\LaLigaApi\Service\Season\updateSeason;
use DMD\LaLigaApi\Dto\SeasonDto;
use DMD\LaLigaApi\Entity\Season;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\SeasonRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\Season\SeasonFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HandleUpdateSeason
{
public function __construct(
public SeasonFactory $seasonSaver,
public EntityManagerInterface $entityManager,
public Security $security,
public SeasonRepository $seasonRepository,
public CustomRoleRepository $customRoleRepository,
public UserRepository $userRepository
){}
public function __invoke(Request $request, int $leagueId, int $seasonId): JsonResponse
{
$seasonObj = $this->checkUserAuthorization($leagueId, $seasonId);
$seasonDto = new SeasonDto();
$seasonDto->fillFromObject($seasonObj);
$seasonDto->fillFromArray($request->toArray());
$seasonDto->validate();
if (!empty($seasonDto->validationErrors))
{
return $this->generateErrorResponse($seasonDto->validationErrors);
}
$seasonObj->setActive(true);
$this->seasonSaver->save($seasonObj, $seasonDto);
$this->entityManager->flush();
return new JsonResponse(
data: [
'success' => true,
'season' => $seasonDto->toArray()
],
status: Response::HTTP_OK
);
}
public function generateErrorResponse(array $validationErrors): JsonResponse
{
return new JsonResponse(
data: [
'success' => false,
'errors' => $validationErrors
],
status: Response::HTTP_OK
);
}
public function checkUserAuthorization(int $leagueId, int $seasonId): Season
{
$user = $this->security->getUser();
if (is_null($user))
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Usuario no encontrado.");
}
$customRole = $this->customRoleRepository->findBy([
'name' => $leagueId.'_LEAGUE_PRESIDENT',
'user' => $user
]);
if (is_null($customRole))
{
throw new HttpException(Response::HTTP_FORBIDDEN, "Usuario no tiene permiso para editar la liga.");
}
$seasonObj = $this->seasonRepository->find($seasonId);
if (is_null($seasonObj))
{
throw new HttpException(Response::HTTP_NOT_FOUND, 'Temporada no encontrada.');
}
return $seasonObj;
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace DMD\LaLigaApi\Service\User\Handlers;
use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserSaver
{
public function __construct(
public EntityManagerInterface $entityManager,
public UserPasswordHasherInterface $passwordHasher,
)
{}
public function save(User $user, UserDto $userDto): User
{
if (!empty($userDto->email))
{
$user->setEmail($userDto->email);
}
if (!empty($userDto->password))
{
$hashedPassword = $this->passwordHasher->hashPassword($user, $userDto->password);
$user->setPassword($hashedPassword);
}
if (!empty($userDto->firstName))
{
$user->setFirstName($userDto->firstName);
}
if (!empty($userDto->lastName))
{
$user->setLastName($userDto->firstName);
}
if (!empty($userDto->birthday))
{
$user->setBirthday($userDto->birthday);
}
if (!empty($userDto->phone))
{
$user->setPhone($userDto->phone);
}
if (!empty($userDto->profilePicture))
{
$user->setProfilePicture($userDto->profilePicture);
}
$this->entityManager->persist($user);
return $user;
}
}
@@ -0,0 +1,43 @@
<?php
namespace DMD\LaLigaApi\Service\User\Handlers\delete;
use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\User\Handlers\UserSaver;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class HandleDeleteUser
{
public function __construct(
public EntityManagerInterface $entityManager,
public UserRepository $userRepository,
){}
public function __invoke(Request $request): JsonResponse
{
$requestArray = $request->toArray();
$existingUser = $this->userRepository->findOneBy(['email'=> $requestArray['email']]);
if (!is_null($existingUser))
{
throw new HttpException(400,'Ya hay un usuario registrado con este correo.');
}
$this->entityManager->remove((object)$existingUser);
$this->entityManager->flush();
$this->entityManager->clear();
return new JsonResponse(
data: [
'success' => true,
'message' => 'Usuario eliminado.'
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,75 @@
<?php
namespace DMD\LaLigaApi\Service\User\Handlers\getNotifications;
use DMD\LaLigaApi\Dto\NotificationDto;
use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Repository\NotificationRepository;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\User\Handlers\UserSaver;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class HandleGetNotifications
{
public function __construct(
public EntityManagerInterface $entityManager,
public NotificationRepository $notificationRepository,
public Security $security
){}
public function __invoke(): JsonResponse
{
$user = $this->security->getUser();
$notifications = $this->notificationRepository->findBy(
criteria: [
'userToNotify' => $user
],
orderBy: [
'createdAt' => 'DESC'
]
);
if (empty($notifications))
{
return new JsonResponse([
'success' => true,
'notifications' => []
], Response::HTTP_OK);
}
$notificationDtoList = [];
foreach ($notifications as $notificationObj)
{
if (
($notificationObj->isIsRead()) &&
(($notificationObj->getReadAt())->diff(new \DateTime('now'))->days > 30)
)
{
$this->entityManager->remove($notificationObj);
continue;
}
if (!$notificationObj->isIsRead())
{
$notificationObj->setIsRead(true);
$notificationObj->setReadAt(new \DateTimeImmutable('now'));
$this->entityManager->persist($notificationObj);
}
$notificationDto = new NotificationDto();
$notificationDtoList[] = ($notificationDto->fillFromObj($notificationObj))->toArray();
}
$this->entityManager->flush();
return new JsonResponse(
data: [
'success' => true,
'notifications' => $notificationDtoList
],
status: Response::HTTP_OK
);
}
}
@@ -0,0 +1,42 @@
<?php
namespace DMD\LaLigaApi\Service\User\Handlers\login;
use DMD\LaLigaApi\Dto\NotificationDto;
use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\User\UserInterface;
class AuthenticationSuccessListener
{
public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event): void
{
$data = $event->getData();
$userDto = new UserDto();
$user = $event->getUser();
if (!$user instanceof User)
{
throw new HttpException(500, 'Internal server error');
}
$notificationEntityList = $user->getReceivedNotifications(); // todo hacer query de notificaciones no leidas
$notificationDtoList = [];
if (!empty($notificationEntityList))
{
foreach ($notificationEntityList as $notificationEntity)
{
$notificationDto = new NotificationDto();
$notificationDto->fillFromObj($notificationEntity);
$notificationDtoList[] = $notificationDto;
}
}
$userDto->notificationDtoList = $notificationDtoList;
$userDto->fillFromObject($user);
$expirationDateTime = (new \DateTime('now', new \DateTimeZone('Europe/Madrid')))->modify('+1800 seconds');
$data['expirationDateTime'] = $expirationDateTime->format('Y-m-d H:i:s');
$data['user'] = $userDto->toArray();
$event->setData($data);
}
}
@@ -0,0 +1,74 @@
<?php
namespace DMD\LaLigaApi\Service\User\Handlers\register;
use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\User\Handlers\UserSaver;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class HandleRegistration
{
public function __construct(
public EntityManagerInterface $entityManager,
public UserSaver $userSaver,
public UserRepository $userRepository,
public JWTTokenManagerInterface $tokenManager,
public ValidatorInterface $validator
){}
public function __invoke(Request $request): JsonResponse
{
$requestArray = $request->toArray();
$existingUser = $this->userRepository->findOneBy([
'email'=> $requestArray['email']
]);
if (!is_null($existingUser))
{
throw new HttpException(400,'Ya hay un usuario registrado con este correo.');
}
$userDto = new UserDto();
$userDto->fillFromArray($requestArray);
$userDto->validate();
if (!empty($userDto->validationErrors))
{
return $this->generateErrorResponse($userDto->validationErrors);
}
$userDto->active = true;
$newUser = new User();
$newUser->setRoles(['ROLE_USER']);
$newUser = $this->userSaver->save($newUser, $userDto);
$this->entityManager->flush();
$this->entityManager->clear();
$userDto->id = $newUser->getId();
$token = $this->tokenManager->create($newUser);
return new JsonResponse(
data: [
'success' => true,
'message' => 'Usuario creado.',
'token' => $token,
'user' => $userDto->toArray(),
],
status: Response::HTTP_OK
);
}
public function generateErrorResponse(array $validationErrors): JsonResponse
{
return new JsonResponse(
data: [
'success' => false,
'errors' => $validationErrors
],
status: Response::HTTP_BAD_REQUEST
);
}
}
@@ -0,0 +1,72 @@
<?php
namespace DMD\LaLigaApi\Service\User\Handlers\update;
use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\User\Handlers\UserSaver;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class HandleUpdateUser
{
public function __construct(
public EntityManagerInterface $entityManager,
public Security $security,
public UserSaver $userSaver,
public UserRepository $userRepository,
public JWTTokenManagerInterface $tokenManager,
public ValidatorInterface $validator
){}
public function __invoke(Request $request): JsonResponse
{
$requestArray = $request->toArray();
$requestUserEmail = $this->security->getUser()?->getUserIdentifier();
$requestUserObj = $this->userRepository->findOneBy([
'email' => $requestUserEmail
]);
if (is_null($requestUserObj))
{
throw new HttpException(500, 'Usuario no encontrado.');
}
$userDto = new UserDto();
$userDto->fillFromObject($requestUserObj);
$userDto->fillFromArray($requestArray);
$userDto->validate();
if (!empty($userDto->validationErrors))
{
$this->generateErrorResponse($userDto->validationErrors);
}
$editedUserObj = $this->userSaver->save($requestUserObj, $userDto);
$this->entityManager->flush();
$this->entityManager->clear();
$userDto->id = $editedUserObj->getId();
return new JsonResponse(
data: [
'success' => true,
'message' => 'Usuario editado.',
'user' => $userDto->toArray(),
],
status: Response::HTTP_OK
);
}
public function generateErrorResponse(array $validationErrors): JsonResponse
{
return new JsonResponse(
data: [
'success' => false,
'errors' => $validationErrors
],
status: Response::HTTP_OK
);
}
}