<?php
namespace App\Controller\Api;
use App\Entity\Convocatoria;
use App\Entity\ConvocatoriaPlayer;
use App\Entity\Customer;
use App\Entity\Player;
use App\Entity\Season;
use App\Entity\Game;
use App\Entity\GameAlignment;
use App\Entity\PlayerSportsInjuries;
use App\Entity\SeasonPlayer;
use App\Entity\GamePlayerStatistics;
use App\Entity\TrainingAsist;
use App\Helper\UploadedBase64File;
use App\Repository\ConvocatoriaRepository;
use App\Repository\PlayerRepository;
use App\Services\Api\PlayerManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Psr\Log\LoggerInterface;
use App\Entity\PlayerWeight;
use DateTime;
class PlayerController extends ApiController
{
/** @var PlayerManager $playerManager */
protected $playerManager;
/**
* @param PlayerManager $playerManager
*/
public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameterBag, PlayerManager $playerManager)
{
parent::__construct($em, $parameterBag);
$this->playerManager = $playerManager;
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/listbygame/{id}", name="api_player_list_by_game", methods={"POST"})
*/
public function listPlayerByGame($id, Request $request)
{
$prefixFile = $this->getParameter("app.path.player_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$request = $this->transformJsonBody($request);
$players = [];
/** @var PlayerRepository $playerRepository */
$playerRepository = $this->em->getRepository(Player::class);
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId()
];
$sort = $request->get('sort');
if (empty($sort)) $sort = 'dorsal';
$direction = $request->get('direction');
if (empty($direction)) $direction = 'ASC';
/** @var Game $game */
$game = $this->em->getRepository(Game::class)->find($id);
$convocatoria = $game->getConvocatoria();
$convocatoriaPlayerRepository = $this->em->getRepository(ConvocatoriaPlayer::class);
/** @var GameAlignment $gameAlignment */
$captain = $game->getAlignment() && $game->getAlignment()->getCaptain()? $game->getAlignment()->getCaptain()->getPlayer()->getId() : null;
/** @var SeasonPlayer $seasonPlayer */
/** @var Player $player */
foreach ($this->em->getRepository(SeasonPlayer::class)->findBy($filter, [$sort => $direction]) as $seasonPlayer) {
$player = $seasonPlayer->getPlayer();
$playerArr = $player->__toArray($baseurl . $prefixFile . "/");
$seasonPlayerActive = !$seasonPlayer->getDeletedAt();
$isActive = $player->getIsActive();
if ($isActive && $seasonPlayerActive) {
$criteria = [
"seasonPlayer" => $seasonPlayer,
"game" => $game
];
$miscellaneous = $playerRepository->getStatsMiscellaneousByGame($player, $game);
$isTitular = $miscellaneous['isTitular'] ? true : false;
$isCaptain = $captain && ($captain == $player->getId());
$out = array_merge($miscellaneous,[
"dorsal" => $seasonPlayer->getDorsal(),
"isTitular" => $isTitular,
"isCaptain" => $isCaptain,
"countryId" => !empty($player->getCountry()) ? $player->getCountry()->getId() : null,
]);
if ($convocatoria) {
$convocatoriaPlayer = $convocatoriaPlayerRepository->findOneBy([
"player_id" => $player->getId(),
"convocatoria_id" => $convocatoria->getId(),
]);
if ($convocatoriaPlayer) {
$out = array_merge($out, [
"isOn" => $convocatoriaPlayer->getIsActive(),
], $convocatoriaPlayer->__toArray());
} else {
$out = array_merge($out, [
"isOn" => false,
"justification_type" => null,
"is_active" => null,
]);
}
} else {
$out = array_merge($out, [
"isOn" => false,
"justification_type" => null,
"is_active" => null,
]);
}
if ($out['isOn']) {
$players[] = array_merge($playerArr, $out);
}
}
}
}
return $this->response($players);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/list", name="api_player_list", methods={"POST"})
*/
public function listPlayer(Request $request)
{
$request = $this->transformJsonBody($request);
$players = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId()
];
$sort = $request->get('sort');
if (empty($sort)) $sort = 'dorsal';
$direction = $request->get('direction');
if (empty($direction)) $direction = 'ASC';
/** @var Player $player */
foreach ($this->em->getRepository(SeasonPlayer::class)->findBy($filter, [$sort => $direction]) as $seasonPlayer) {
/** @var SeasonPlayer $seasonPlayer */
$player = $seasonPlayer->getPlayer();
$seasonPlayerActive = !$seasonPlayer->getDeletedAt();
$isActive = $player->getIsActive();
if ($isActive && !$player->getDeletedAt() && $seasonPlayerActive) {
$players[] = $this->getDataPlayer($request, $player, $season);
}
}
}
return $this->response($players);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/list/recycling", name="api_player_list_recycling", methods={"POST"})
*/
public function listPlayerRecycling(Request $request)
{
$request = $this->transformJsonBody($request);
$players = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId()
];
$sort = $request->get('sort');
if (empty($sort)) $sort = 'dorsal';
$direction = $request->get('direction');
if (empty($direction)) $direction = 'ASC';
/** @var Player $player */
foreach ($this->em->getRepository(SeasonPlayer::class)->findBy($filter, [$sort => $direction]) as $seasonPlayer) {
/** @var SeasonPlayer $seasonPlayer */
$player = $seasonPlayer->getPlayer();
$seasonPlayerActive = $seasonPlayer->getIsActive();
$seasonPlayerDeletedAt = $seasonPlayer->getDeletedAt();
if ($player->getDeletedAt() && $player->getIsActive() && $seasonPlayerActive && $seasonPlayerDeletedAt) {
$players[] = $this->getDataPlayer($request, $player, $season);
}
}
}
return $this->response($players);
}
public function getDataPlayer(Request $request, Player $player, Season $season)
{
$seasonPlayer = $this->em->getRepository(SeasonPlayer::class)->findOneBy(['player' => $player, "season" => $season]);
$weights = [];
foreach ($this->em->getRepository(PlayerWeight::class)->findBy([
'seasonPlayer' => $seasonPlayer
], ['date' => 'ASC']) as $key => $weight) {
$weights[] = $weight->__toArray();
}
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$prefixFile = $this->getParameter("app.path.player_images");
/** @var PlayerRepository $playerRepository */
$playerRepository = $this->em->getRepository(Player::class);
$playerArr = $player->__toArray($baseurl . $prefixFile . "/");
$playerArr['weights'] = $weights;
$playerArr['weight'] = count($weights) ? $weights[0]['weight'] : $playerArr['weight'];
// add weight if is empty table PlayerWeight player
if (!count($weights) && $playerArr['weight'] != 0.00) {
$playerWeight = new PlayerWeight();
$playerWeight->setSeasonPlayer($seasonPlayer);
$playerWeight->setWeight($playerArr['weight']);
$playerWeight->setDate(new DateTime());
$playerWeight->setTime(new DateTime());
$this->em->persist($playerWeight);
$this->em->flush();
$playerArr['weights'] = $playerWeight->__toArray();
}
$miscellaneous = $playerRepository->getStatsMiscellaneousAllPlayers($player, $season);
$trainingAsist = $playerRepository->getStatsAsist($player, $season);
$result = $playerRepository->getStatsConvocatoria($player, $season);
$newData = array_merge($playerArr, $miscellaneous);
$newData = array_merge($trainingAsist, $newData);
$newData = array_merge($result, $newData);
return array_merge($newData, [
"dorsal" => $seasonPlayer->getDorsal(),
"countryId" => !empty($player->getCountry()) ? $player->getCountry()->getId() : null,
"seasonsPlayer" => $player->getSeasonPlayers()->map(function (SeasonPlayer $seasonPlayer) use ($playerRepository, $player, $request) {
$season = $seasonPlayer->getSeason();
$miscellaneous = $playerRepository->getStatsMiscellaneousAllPlayers($player, $season);
$imageTeam = $season->getTeam()->getImage();
$prefixFile = $this->getParameter("app.path.customer_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$imagePath = !empty($imageTeam) ? $baseurl . $prefixFile . "/" . $imageTeam : "";
$miscellaneous['imageTeam'] = $imagePath;
return array_merge($seasonPlayer->__toArray(), $miscellaneous);
})->toArray(),
]);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/add", name="api_player_add", methods={"POST"})
*/
public function addPlayer(Request $request)
{
$request = $this->transformJsonBody($request);
$data = $this->getDataFromRequest($request);
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
$response = $this->playerManager->add($data, $request);
$this->setStatusCode($response["code"]);
if ($response['code'] == 200) {
$response['player'] = $this->getDataPlayer($request, $response['player'], $season);
};
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/players/all", name="api_players_all", methods={"POST"})
*/
public function allPlayers(Request $request)
{
$customer = $this->getUser();
$response = $this->playerManager->allPlayersByUserId($customer);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/players/migrate/{seasonId}", name="api_players_migrate", methods={"POST"})
*/
public function migratePlayer($seasonId, Request $request)
{
$customer = $this->getUser();
$season = $customer->getSeasonActive();
$players = json_decode($request->get('players', "[]"), true);
$seasonRepository = $this->em->getRepository(Season::class);
/** @var Season $seasonTarget */
$seasonTarget = $seasonRepository->findOneBy(["id" => $seasonId, "customer" => $customer->getId(), "isActive" => true]);
$response = $this->playerManager->addPlayerToSeason($customer, $season, $players, $seasonTarget);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/players/migrate/undo/{seasonId}", name="api_players_migrate_undo", methods={"POST"})
*/
public function undoMigratePlayer($seasonId, Request $request)
{
$customer = $this->getUser();
$season = $customer->getSeasonActive();
$players = json_decode($request->get('players', "[]"), true);
$seasonRepository = $this->em->getRepository(Season::class);
/** @var Season $seasonTarget */
$seasonTarget = $seasonRepository->findOneBy(["id" => $seasonId, "customer" => $customer->getId(), "isActive" => true]);
$response = $this->playerManager->moveToBinPlayerFromSeason($customer, $season, $players, $seasonTarget);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/players/migrate/remove/{seasonId}", name="api_players_migrate_remove", methods={"POST"})
*/
public function removeMigratePlayer($seasonId, Request $request)
{
$customer = $this->getUser();
$season = $customer->getSeasonActive();
$players = json_decode($request->get('players', "[]"), true);
$seasonRepository = $this->em->getRepository(Season::class);
/** @var Season $seasonTarget */
$seasonTarget = $seasonRepository->findOneBy(["id" => $seasonId, "customer" => $customer->getId(), "isActive" => true]);
$response = $this->playerManager->removePlayerFromSeason($customer, $season, $players, $seasonTarget);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/players/migrate/rollback/{seasonId}", name="api_players_migrate_rollback", methods={"POST"})
*/
public function rollbackMigratePlayer($seasonId, Request $request)
{
$customer = $this->getUser();
$season = $customer->getSeasonActive();
$players = json_decode($request->get('players', "[]"), true);
$seasonRepository = $this->em->getRepository(Season::class);
/** @var Season $seasonTarget */
$seasonTarget = $seasonRepository->findOneBy(["id" => $seasonId, "customer" => $customer->getId(), "isActive" => true]);
$response = $this->playerManager->removePlayerFromSeason($customer, $season, $players, $seasonTarget);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/edit/{player}", name="api_player_edit", methods={"POST"})
*/
public function editPlayer(Player $player, Request $request, LoggerInterface $logger)
{
$request = $this->transformJsonBody($request);
$data = $this->getDataFromRequest($request);
$response = $this->playerManager->edit($player, $data);
$logger->info("DATA " . json_encode($data));
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/editstats/{player}", name="api_player_editstats", methods={"POST"})
*/
public function editStats(Player $player, Request $request, LoggerInterface $logger)
{
$data = [
"gameId" => $request->get('gameId'),
"minutes" => $request->get('minutes'),
"yellowCards" => $request->get('yellowCards'),
"redCards" => $request->get('redCards'),
"goals" => $request->get('goals'),
"goalAssistances" => $request->get('goalAssistances'),
"isTitular" => $request->get('isTitular'),
"kilometersTraveled" => $request->get('kilometersTraveled'),
"shotsOnGoal" => $request->get('shotsOnGoal'),
"stolenBalls" => $request->get('stolenBalls'),
"penaltiesCommitted" => $request->get('penaltiesCommitted'),
"forcedPenalties" => $request->get('forcedPenalties'),
"stopsMade" => $request->get('stopsMade'),
];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
$response = $this->playerManager->updateStats($player, $data, false);
$this->setStatusCode($response["code"]);
if ($response['code'] == 200) {
$response['player'] = $this->getDataPlayer($request, $response['player'], $season);
};
return $this->response($response);
}
protected function getDataFromRequest(Request $request)
{
$data = [
"name" => $request->get('name'),
"lastname" => $request->get('lastname'),
"position" => $request->get('position'),
"secondary_position" => $request->get('secondaryPosition'),
"age" => (int) $request->get('age'),
"weight" => (float) $request->get('weight'),
"height" => (float) $request->get('height'),
"shoes" => (int) $request->get('shoes'),
"games" => (int) $request->get('games'),
"goals" => (int) $request->get('goals'),
"yellowCard" => (int) $request->get('yellowCard'),
"redCard" => (int) $request->get('redCard'),
"dorsal" => (int) $request->get('dorsal'),
"skillfulLeg" => (int) $request->get('skillfulLeg'),
"countryId" => (int) $request->get('countryId'),
"phone" => $request->get('phone') ?? NULL,
"email" => $request->get('email') ?? NULL,
"numberDocument" => $request->get('numberDocument') ?? NULL,
"healthCard" => $request->get('healthCard') ?? NULL,
"dateOfBirth" => $request->get('dateOfBirth') ? new DateTime($request->get('dateOfBirth')) : NULL,
"medicalReviewDate" => $request->get('medicalReviewDate') ? new DateTime($request->get('medicalReviewDate')) : NULL,
"lastClub" => $request->get('lastClub') ?? NULL,
];
$image = $request->get('image');
if (!empty($image))
$data["image"] = new UploadedBase64File($image, $request->get('imageFilename'));
return $data;
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/trainingAsist", name="api_player_trainingAsist", methods={"POST"})
*/
public function trainingAsistPlayer(Request $request)
{
$prefixFile = $this->getParameter("app.path.player_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$order = $request->get('order', 'trainingAsist');
$players = [];
/** @var PlayerRepository $playerRepository */
$playerRepository = $this->em->getRepository(Player::class);
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId()
];
/** @var SeasonPlayer $seasonPlayer */
/** @var Player $player */
foreach ($this->em->getRepository(SeasonPlayer::class)->findBy($filter) as $seasonPlayer) {
$player = $seasonPlayer->getPlayer();
$seasonPlayerActive = !$seasonPlayer->getDeletedAt();
$isActive = $player->getIsActive();
if ($isActive && $seasonPlayerActive) {
$result = $playerRepository->getStatsAsist($player, $season);
// Retrieve min statistics and league statistics
$playerMinutes = $this->em->getRepository(GamePlayerStatistics::class)->getPlayerMinutes($seasonPlayer->getId());
$totalMinutes = (int) $playerMinutes['totalMinutes'];
$leagueMinutes = (int) $playerMinutes['leagueMinutes'];
$players[] = [
"id" => $player->getId(),
"name" => $player->getName(),
"lastname" => $player->getLastname(),
"position" => !empty($player->getPosition()) ? $player->getPosition()->getSlug() : "",
"image" => !empty($player->getImage()) ? $baseurl . $prefixFile . "/" . $player->getImage() : "",
"trainingAsist" => intval($result['trainingAsist'] ?? 0),
"trainingAsistTotal" => intval($result['trainingAsistTotal'] ?? 0),
"trainingAsistPercent" => intval($result['trainingAsistPercent'] ?? 0),
"totalMinutes" => $totalMinutes,
"leagueMinutes" => $leagueMinutes,
];
}
}
usort($players, function ($a, $b) use ($order) {
if ($a[$order] > $b[$order])
return 1;
if ($a[$order] < $b[$order])
return -1;
return 0;
});
$players = array_reverse($players);
}
return $this->response($players);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/convocatorias", name="api_player_convocatorias", methods={"POST"})
*/
public function convocatoriasPlayer(Request $request)
{
$prefixFile = $this->getParameter("app.path.player_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$request = $this->transformJsonBody($request);
$players = [];
/** @var PlayerRepository $playerRepository */
$playerRepository = $this->em->getRepository(Player::class);
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId()
];
/** @var ConvocatoriaRepository $convocatoriaRepository */
$convocatoriaRepository = $this->em->getRepository(Convocatoria::class);
/** @var SeasonPlayer $seasonPlayer */
/** @var Player $player */
foreach ($this->em->getRepository(SeasonPlayer::class)->findBy($filter) as $seasonPlayer) {
$player = $seasonPlayer->getPlayer();
$seasonPlayerActive = !$seasonPlayer->getDeletedAt();
$isActive = $player->getIsActive();
if ($isActive && $seasonPlayerActive) {
$result = $playerRepository->getStatsConvocatoria($player, $season);
$players[] = array_merge([
"id" => $player->getId(),
"name" => $player->getName(),
"lastname" => $player->getLastname(),
"position" => !empty($player->getPosition()) ? $player->getPosition()->getSlug() : "",
"image" => !empty($player->getImage()) ? $baseurl . $prefixFile . "/" . $player->getImage() : "",
],$result);
}
}
usort($players, function ($a, $b) {
if ($a["convocatory"] > $b["convocatory"])
return 1;
if ($a["convocatory"] < $b["convocatory"])
return -1;
return 0;
});
$players = array_reverse($players);
}
return $this->response($players);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/assistances/{id}/{month}/{year}", name="api_player_assistances", methods={"POST"})
*/
public function assistancesPlayer($id, $month, $year)
{
/** @var Player $player */
$player = $this->em->getRepository(Player::class)->findOneBy(['id' => $id]);
$lowermonth = \DateTime::createFromFormat("d/m/Y H:i:s", "1/" . ($month) . "/" . ($year) . " 00:00:00");
$uppermonth = \DateTime::createFromFormat("d/m/Y H:i:s", "0/" . ($month + 1) . "/" . ($year) . " 00:00:00");
$dates = [];
$dates['justifications'] = [];
$justifications = $player->getJustification();
foreach ($justifications as $justification) {
if ($justification->getDate() >= $lowermonth && $justification->getDate() <= $uppermonth) {
$dates['justifications'][] = [
"date" => $justification->getDate()->format("Y-m-d"),
"type" => $justification->getJustificationType()->getId()
];
}
};
$dates['assistances'] = [];
$trainingsAssits = $player->getTrainingAsists();
foreach ($trainingsAssits as $trainingAssist) {
if ($trainingAssist->getDate() >= $lowermonth && $trainingAssist->getDate() <= $uppermonth)
$dates['assistances'][] = [
"date" => $trainingAssist->getDate()->format("Y-m-d")
];
};
$dates['lacks'] = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
[
"prop" => "season",
"comp" => "=",
"val" => $season->getId()
],
[
"prop" => "date",
"comp" => ">=",
"val" => $lowermonth
],
[
"prop" => "date",
"comp" => "<=",
"val" => $uppermonth
],
];
/** @var TrainingAsist $trainingAsist */
foreach ($this->em->getRepository(TrainingAsist::class)->findByOwnCriteria($filter) as $trainingAsist) {
$date = $trainingAsist->getDate()->format("Y-m-d");
if (!in_array($date, array_column($dates['justifications'], 'date')) && !in_array($date, array_column($dates['assistances'], 'date'))) {
$dates['lacks'][] = [
"date" => $date
];
}
}
}
return $this->response($dates);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/assistance/{id}/{month}", name="api_player_assistance", methods={"POST"})
*/
public function assistancePlayer($id, $month)
{
/** @var Player $player */
$player = $this->em->getRepository(Player::class)->findOneBy(['id' => $id]);
$lowermonth = \DateTime::createFromFormat("d/m/Y H:i:s", "1/" . ($month) . "/" . date('Y') . " 00:00:00");
$uppermonth = \DateTime::createFromFormat("d/m/Y H:i:s", "0/" . ($month + 1) . "/" . date('Y') . " 00:00:00");
$dates = [];
$dates['justifications'] = [];
$justifications = $player->getJustification();
foreach ($justifications as $justification) {
if ($justification->getDate() >= $lowermonth && $justification->getDate() <= $uppermonth) {
$dates['justifications'][] = [
"date" => $justification->getDate()->format("Y-m-d"),
"type" => $justification->getJustificationType()->getId()
];
}
};
$dates['assistances'] = [];
$trainingsAssits = $player->getTrainingAsists();
foreach ($trainingsAssits as $trainingAssist) {
if ($trainingAssist->getDate() >= $lowermonth && $trainingAssist->getDate() <= $uppermonth)
$dates['assistances'][] = [
"date" => $trainingAssist->getDate()->format("Y-m-d")
];
};
$dates['lacks'] = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
[
"prop" => "season",
"comp" => "=",
"val" => $season->getId()
],
[
"prop" => "date",
"comp" => ">=",
"val" => $lowermonth
],
[
"prop" => "date",
"comp" => "<=",
"val" => $uppermonth
],
];
/** @var TrainingAsist $trainingAsist */
foreach ($this->em->getRepository(TrainingAsist::class)->findByOwnCriteria($filter) as $trainingAsist) {
$date = $trainingAsist->getDate()->format("Y-m-d");
if (!in_array($date, array_column($dates['justifications'], 'date')) && !in_array($date, array_column($dates['assistances'], 'date'))) {
$dates['lacks'][] = [
"date" => $date
];
}
}
}
return $this->response($dates);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/delete/{player}", name="api_player_delete", methods={"POST"})
*/
public function deletePlayer(Player $player)
{
$response = $this->playerManager->delete($player);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/delete/{player}/permanent", name="api_player_delete_permanent", methods={"POST"})
*/
public function deletePlayerPermanent(Player $player)
{
$response = $this->playerManager->deletePermanent($player);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/restore/{player}", name="api_player_restore", methods={"POST"})
*/
public function restorePlayer(Player $player)
{
$response = $this->playerManager->restorePlayer($player);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/games/{id}", name="api_player_games", methods={"POST"})
*/
public function gamesPlayer($id, Request $request)
{
$prefixFile = $this->getParameter("app.path.game_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
/** @var PlayerRepository $playerRepository */
$playerRepository = $this->em->getRepository(Player::class);
$player = $playerRepository->findOneBy([
'id' => $id
]);
$results = $playerRepository->findGamesBySeason($player, $season);
/** @var PlayerRepository $playerRepository */
$gameRepository = $this->em->getRepository(Game::class);
$output = [];
foreach ($results as $result) {
$game = $gameRepository->findOneBy([
'id' => $result['id']
])->__toArray($baseurl . $prefixFile . "/");
$game['playerStats'] = $result;
$output[] = $game;
}
return $this->response($output);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/justifications", name="api_player_justifications", methods={"POST"})
*/
public function justifications(Request $request)
{
$prefixFile = $this->getParameter("app.path.player_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$order = $request->get('order', 'justificationTotal');
$players = [];
/** @var PlayerRepository $playerRepository */
$playerRepository = $this->em->getRepository(Player::class);
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId()
];
/** @var SeasonPlayer $seasonPlayer */
/** @var Player $player */
foreach ($this->em->getRepository(SeasonPlayer::class)->findBy($filter) as $seasonPlayer) {
$player = $seasonPlayer->getPlayer();
$seasonPlayerActive = !$seasonPlayer->getDeletedAt();
$isActive = $player->getIsActive();
$playerSportInjure = [
'season' => $season,
'seasonPlayer' => $seasonPlayer
];
$playerInjury = [];
foreach ($this->em->getRepository(PlayerSportsInjuries::class)->findBy($playerSportInjure) as $key => $injury) {
$playerInjury[] = $injury->__toArray();
}
if ($isActive && $seasonPlayerActive) {
$justifications = $playerRepository->getStatsJustification($player, $season);
$justificationsConvocatoria = $playerRepository->getStatsJustificationConvocatoria($player, $season);
$base = [
"id" => $player->getId(),
"name" => $player->getName(),
"lastname" => $player->getLastname(),
"position" => !empty($player->getPosition()) ? $player->getPosition()->getSlug() : "",
"image" => !empty($player->getImage()) ? $baseurl . $prefixFile . "/" . $player->getImage() : "",
"playerInjuriesGames" => $playerInjury
];
$players[] = array_merge($base, $justifications, $justificationsConvocatoria);
}
}
usort($players, function ($a, $b) use ($order) {
if ($a[$order] > $b[$order])
return 1;
if ($a[$order] < $b[$order])
return -1;
return 0;
});
$players = array_reverse($players);
}
return $this->response($players);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/{id}/seasons", name="api_player_seasons", methods={"POST"})
*/
public function seasons(Request $request)
{
$prefixFile = $this->getParameter("app.path.player_images");
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$order = $request->get('order', 'justificationTotal');
$players = [];
/** @var PlayerRepository $playerRepository */
$playerRepository = $this->em->getRepository(Player::class);
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
if (!empty($season)) {
$filter = [
"season" => $season->getId()
];
/** @var SeasonPlayer $seasonPlayer */
/** @var Player $player */
foreach ($this->em->getRepository(SeasonPlayer::class)->findBy($filter) as $seasonPlayer) {
$player = $seasonPlayer->getPlayer();
$seasonPlayerActive = !$seasonPlayer->getDeletedAt();
$isActive = $player->getIsActive();
if ($isActive && $seasonPlayerActive) {
$justifications = $playerRepository->getStatsJustification($player, $season);
$justificationsConvocatoria = $playerRepository->getStatsJustificationConvocatoria($player, $season);
$base = [
"id" => $player->getId(),
"name" => $player->getName(),
"lastname" => $player->getLastname(),
"position" => !empty($player->getPosition()) ? $player->getPosition()->getSlug() : "",
"image" => !empty($player->getImage()) ? $baseurl . $prefixFile . "/" . $player->getImage() : "",
];
$players[] = array_merge($base, $justifications, $justificationsConvocatoria);
}
}
usort($players, function ($a, $b) use ($order) {
if ($a[$order] > $b[$order])
return 1;
if ($a[$order] < $b[$order])
return -1;
return 0;
});
$players = array_reverse($players);
}
return $this->response($players);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player/search_customer_shared", name="api_search_customer_shared_", methods={"POST"})
*/
public function searchCustomerSharedPlayer(Request $request)
{
if (!$request->get('email')) {
return $this->response(['code' => 422, 'message' => 'email is required']);
}
$customerRepository = $this->em->getRepository(Customer::class);
$customer = $customerRepository->findOneBy(["email" => $request->get("email")]);
if ($customer) {
return $this->response([
'code' => 200,
'data' => [
'id' => $customer->getId(),
'name' => $customer->getName(),
'teamName' => $customer->getNameTeam(),
'email' => $customer->getEmail(),
]
]);
}
return $this->response([
'code' => 401,
'message' => 'user not fount!',
]);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/players/season-squad/evaluate", name="api_season_players_evaluate", methods={"POST"})
*/
public function evalutePlayerBySeason(Request $request)
{
$request = $this->transformJsonBody($request);
$players = [];
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
$response = $this->playerManager->isOverTheCap($customer, $season);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/player-league/stats/{player}", name="api_season_player_league_stats", methods={"POST"})
*/
public function playerLeagueStats(Player $player, Request $request)
{
$request = $this->transformJsonBody($request);
/** @var Customer $customer */
$customer = $this->getUser();
$season = $customer->getSeasonActive();
$seasonPlayer = $this->getSeasonPlayer($player, $season);
/** @var PlayerRepository $playerRepository */
$gameRepository = $this->em->getRepository(Game::class);
$playerLeagueStats = $gameRepository->getSeasonPlayerStats($seasonPlayer->getId());
return $this->response($playerLeagueStats);
}
public function getSeasonPlayer(Player $player, Season $season)
{
$seasonPlayer = $this->em->getRepository(SeasonPlayer::class)->findOneBy(['player' => $player, "season" => $season]);
return $seasonPlayer;
}
}