<?php
// src/Controller/BaseController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Validator\ConstraintViolationList;
use Orc\SaasBundle\Entity\Client;
use Orc\BookingBundle\Repository\HoursOfOperationRepository;
use Orc\BookingBundle\Repository\HoursChangeRepository;
use Orc\BookingBundle\Entity\Booking;
use Orc\BookingBundle\Booking\EndTimeCalculator;
use App\Entity\BookingProcess;
use App\Entity\BookingProcessBooking;
use App\Entity\BookingProcessBookingNote;
use App\Entity\BookingProcessBookingServiceAnswer;
use App\Entity\BookingProcessLocation;
use App\Model\GoogleCalendarModel;
use App\Model\Google\GoogleClient;
use App\Model\Google\Entity\WatchGoogleChannelParams;
class BaseController extends AbstractController {
protected $client;
protected $site;
protected $entityManager;
protected function addOrUpdateGoogleEvent(
Request $request, GoogleClient $googleClient,
GoogleCalendarModel $googleCalendarModel, Booking $booking
) : void
{
// try {
$events = $googleCalendarModel->getStaffCalendarsBookingEvents(
$this->client, $booking
);
foreach($events as $event) {
$event->getGoogleCalendarEvent()->setDescription($this->renderView(
'@OrcCalendar/Feed/feed-description.ical.twig',
[
'booking' => $event->getBooking(),
'worker' => $event->getWorker(),
'site' => $this->client->getSite()
]
));
}
$googleCalendarModel->addEvents($events);
// }
// catch (CalendarModelException $exc) {
// $this->addFlash(
// "error",
// "Unable to fully sync booking event with google calendar. "
// . "Please <a href=\"". $this->generateUrl('app_google_calendar_addstaffcalendars') ."\">re-sync with google calendar</a>."
// );
// }
}
/**
*
* @param GoogleClient $googleClient
* @return bool
*/
protected function authenticate(
Request $request, GoogleClient $googleClient
) : bool
{
$client = $this->getClient();
$this->get('session')->set('original_url', $request->getUri());
$isAuthenticated = $googleClient->setRedirectUrl(
$this->getGoogleOauthRedirectUrl()
)->authenticate($this->get('session')->get('original_url'));
return $isAuthenticated;
}
function getClient() {
$hostName = $this->container->get('request_stack')
->getCurrentRequest()
->server->get('SERVER_NAME');
if (preg_match('/^admin\./', $hostName)) {
return null;
}
$this->entityManager = $this->getDoctrine()->getManager();
$clientRepository = $this->entityManager->getRepository(Client::class);
$this->client = $clientRepository->findOneByDomainAdvanced($hostName);
//$this->client = $clientRepository->findOneByDomain($hostName);
if (empty($this->client)) {
throw $this->createNotFoundException('Tenant not found.');
}
$this->site = $this->client->getSite();
return $this->client;
}
function getEntityManager() {
$this->entityManager = $this->getDoctrine()->getManager();
return $this->entityManager;
}
function getClientFromRequest(Request $request) {
$hostName = $request->server->get('SERVER_NAME');
if (preg_match('/^admin\./', $hostName)) {
return null;
}
$this->entityManager = $this->getDoctrine()->getManager();
$clientRepository = $this->entityManager->getRepository(Client::class);
$this->client = $clientRepository->findOneByDomainAdvanced($hostName);
//$this->client = $clientRepository->findOneByDomain($hostName);
if (empty($this->client)) {
throw $this->createNotFoundException('Tenant not found.');
}
$this->site = $this->client->getSite();
return $this->client;
}
function getClientFromUrl(string $url) {
$url = str_replace('https://', '', $url);
$arrUrl = explode('/', $url);
$hostName = $arrUrl[0];
if (preg_match('/^admin\./', $hostName)) {
return null;
}
$this->entityManager = $this->getDoctrine()->getManager();
$clientRepository = $this->entityManager->getRepository(Client::class);
$this->client = $clientRepository->findOneByDomainAdvanced($hostName);
//$this->client = $clientRepository->findOneByDomain($hostName);
if (empty($this->client)) {
throw $this->createNotFoundException('Tenant not found.');
}
$this->site = $this->client->getSite();
return $this->client;
}
protected function getErrorMessages($form) {
$errors = array();
foreach ($form->getErrors() as $key => $error) {
if ($form->isRoot()) {
$errors['#'][] = $error->getMessage();
} else {
$errors[] = $error->getMessage();
}
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors[$child->getName()] = $this->getErrorMessages($child);
}
}
return $errors;
}
/**
*
* @return string
*/
protected function getGoogleOauthRedirectUrl() : string
{
$redirectUrl = $this->generateUrl(
'app_google_oauthcallback', [], UrlGeneratorInterface::ABSOLUTE_URL
);
$arrUrl = explode('.', $redirectUrl);
$arrUrl[0] = 'https://admin';
$redirectUrl = implode('.', $arrUrl);
return $redirectUrl;
}
protected function getWatchGoogleChannelParams($client)
{
$domain = $this->getParameter('domain_name');
$adminSubdomain = $this->getParameter('admin_subdomain');
$googleWebHookUrl = 'https://' . $adminSubdomain . '.' . $domain .
$this->generateUrl('app_google_calendar_eventschannelwebhook');
return new WatchGoogleChannelParams(
$client,
new \Google_Service_Calendar_Channel(),
$googleWebHookUrl,
$domain
);
}
protected function determineCalendarQueryStart(
\DateTime $start, Booking $booking,
HoursOfOperationRepository $hoursOfOperationRepository,
EndTimeCalculator $endTimeCalculator,
HoursChangeRepository $hoursChangeRepository
)
{
$cutofftime = $booking->getService()->getCutofftime();
$start->modify($cutofftime . ' hours');
$start = $this->determineCalendarQueryStartRound(
$start, $booking, $hoursOfOperationRepository, $endTimeCalculator,
$hoursChangeRepository
);
return $start;
}
protected function determineCalendarQueryStartRound(
\DateTime $start, Booking $booking,
HoursOfOperationRepository $hoursOfOperationRepository,
EndTimeCalculator $endTimeCalculator,
HoursChangeRepository $hoursChangeRepository
)
{
$dayEndTime = $this->getDayEndTime(
$start, $hoursOfOperationRepository, $hoursChangeRepository
);
$dayEndTime->setDate($start->format('Y'), $start->format('m'), $start->format('d'));
$dayEndTime->modify('-' . $endTimeCalculator->getTimeRequired($booking) . ' minutes');
if ( $start > $dayEndTime ) {
$start->modify('1 day');
$dayStartTime = $this->getDayStartTime(
$start, $hoursOfOperationRepository, $hoursChangeRepository
);
$start->setTime($dayStartTime->format('H'), $dayStartTime->format('i'));
$start = $this->determineCalendarQueryStartRound(
$start, $booking, $hoursOfOperationRepository,
$endTimeCalculator, $hoursChangeRepository
);
}
return $start;
}
protected function determineCalendarQueryStartForProcess(
\DateTime $start, BookingProcessBooking $booking,
HoursOfOperationRepository $hoursOfOperationRepository,
EndTimeCalculator $endTimeCalculator,
HoursChangeRepository $hoursChangeRepository
)
{
$cutofftime = $booking->getService()->getCutofftime();
$start->modify($cutofftime . ' hours');
$start = $this->determineCalendarQueryStartRoundForProcess(
$start, $booking, $hoursOfOperationRepository, $endTimeCalculator,
$hoursChangeRepository
);
return $start;
}
protected function determineCalendarQueryStartRoundForProcess(
\DateTime $start, BookingProcessBooking $booking,
HoursOfOperationRepository $hoursOfOperationRepository,
EndTimeCalculator $endTimeCalculator,
HoursChangeRepository $hoursChangeRepository
)
{
$dayEndTime = $this->getDayEndTime(
$start, $hoursOfOperationRepository, $hoursChangeRepository
);
$olddayEndTime1 = clone($dayEndTime);
$dayEndTime->setDate($start->format('Y'), $start->format('m'), $start->format('d'));
$olddayEndTime2 = clone($dayEndTime);
$dayEndTime->modify('-' . $endTimeCalculator->getTimeRequiredForProcess($booking) . ' minutes');
// if ($start->format('d') == '26') {
// dd(['start' => $start, 'dayEndTime' => $dayEndTime, 'olddayEndTime1' => $olddayEndTime1, 'olddayEndTime2' => $olddayEndTime2, 'modify' => '-' . $endTimeCalculator->getTimeRequiredForProcess($booking) . ' minutes']);
// }
if ( $start > $dayEndTime ) {
$start->modify('1 day');
$dayStartTime = $this->getDayStartTime(
$start, $hoursOfOperationRepository, $hoursChangeRepository
);
$start->setTime($dayStartTime->format('H'), $dayStartTime->format('i'));
$start = $this->determineCalendarQueryStartRoundForProcess(
$start, $booking, $hoursOfOperationRepository,
$endTimeCalculator, $hoursChangeRepository
);
}
return $start;
}
private function getDayEndTime(
\DateTime $start,
HoursOfOperationRepository $hoursOfOperationRepository,
HoursChangeRepository $hoursChangeRepository
)
{
$day = clone $start;
$day->setTime(0, 0);
$hoursChange = $hoursChangeRepository->findOneBy([
'client' => $this->client,
'day' => $day
]);
if ($hoursChange) {
$dayEndTime = clone $hoursChange->getEndTime();
}
else {
$dayOfTheWeekNumber = $start->format('N')%7;
$dayHoursOfOperation = $hoursOfOperationRepository->findOneBy([
'client' => $this->client,
'day' => $dayOfTheWeekNumber
]);
$dayEndTime = clone $dayHoursOfOperation->getEndTime();
}
return $dayEndTime;
}
private function getDayStartTime(
\DateTime $start,
HoursOfOperationRepository $hoursOfOperationRepository,
HoursChangeRepository $hoursChangeRepository
)
{
$day = clone $start;
$day->setTime(0, 0);
$hoursChange = $hoursChangeRepository->findOneBy([
'client' => $this->client,
'day' => $day
]);
if ($hoursChange) {
$dayStartTime = clone $hoursChange->getStartTime();
}
else {
$dayOfTheWeekNumber = $day->format('N')%7;
$dayHoursOfOperation = $hoursOfOperationRepository->findOneBy([
'client' => $this->client,
'day' => $dayOfTheWeekNumber
]);
$dayStartTime = clone $dayHoursOfOperation->getStartTime();
}
return $dayStartTime;
}
protected function toValidationErrors(ConstraintViolationList $violationList, string $prefix=null) : array
{
$errors = [];
foreach($violationList as $violation) {
$key = $violation->getPropertyPath();
if ($prefix){
$key = $prefix . $key;
}
$errors[$key] = $violation->getMessage();
}
return $errors;
}
protected function resize($imagePath, $width, $height)
{
$im = new \Imagick($imagePath);
$im = $im->flattenImages();
$im->setImageFormat('jpg');
$im->resizeImage($width,$height, \imagick::FILTER_LANCZOS, 0.9, true);
$imagePath = $this->ChangeExtensionToJpg($imagePath);
$im->writeImage($imagePath);
return $imagePath;
}
protected function ChangeExtensionToJpg($filenameWithPath)
{
$path_parts = pathinfo($filenameWithPath);
$fileExtension = $path_parts['extension'];
unlink($filenameWithPath);
return preg_replace('/\.' . $fileExtension . '$/', '.jpg', $filenameWithPath);
}
protected function getFileName($filenameWithPath)
{
$path_parts = pathinfo($filenameWithPath);
return $path_parts['filename'] . '.' . $path_parts['extension'];
}
}