public function onKernelTerminate(PostResponseEvent $event) { /** @var Request $request */ $request = $event->getRequest(); if (!$this->isEnable || !$this->isLoggableRequest($request)) { return; } try { /** @var Response $response */ $response = $event->getResponse(); $route = $request->get('_route'); $content = $this->cleanSensitiveContent($route, $request->getContent()); $token = $this->tokenStorage->getToken(); $user = !is_null($token) ? $token->getUser() : null; $logRequest = new LogRequest(); $logRequest->setRoute($route)->setPath($request->getPathInfo())->setMethod($request->getMethod())->setQuery(urldecode($request->getQueryString()))->setContent($content)->setStatus($response->getStatusCode())->setIp($request->getClientIp())->setUser(!is_string($user) ? $user : null); if ($this->logResponse($response)) { $logRequest->setResponse($response->getContent()); } $this->em->persist($logRequest); $this->em->flush(); } catch (\Exception $e) { $this->logger->error(sprintf("LogRequest couldn't be persist : %s", $e->getMessage())); } }
public function onKernelRequest(GetResponseEvent $event) { $this->logger->debug('Entity builder listener: catch kernel.request event'); // If this is not a master request, skip handling if (!$event->isMasterRequest()) { $this->logger->debug('Entity builder listener: this is not master request, skip'); return; } // If content already prepared if ($event->hasResponse()) { $this->logger->debug('Entity builder listener: event already has response, skip'); return; } // Getting request $request = $event->getRequest(); // Getting action $apiServerAction = $event->getRequest()->attributes->get('apiAction'); /* @var $apiServerAction ApiServerAction */ // Something wrong if (!$apiServerAction) { $this->logger->error('Request parser listener: request has no apiAction attribute, throwing access denied exception'); throw new AccessDeniedHttpException(); } // Creating request data entity try { $apiEntity = $apiServerAction->getRequestedEntity($request->attributes->get('apiData')); } catch (\Exception $e) { $this->logger->notice(sprintf('Request parser listener: unable to convert apiData to entity ("%s"), apiEntity set tu null', $e->getMessage())); $apiEntity = null; } // Setting request attributes $request->attributes->set('requestData', $apiEntity); // Cleaning request attributes $request->attributes->remove('apiData'); }
public function onKernelException(GetResponseForExceptionEvent $event) { $this->logger->notice(sprintf('Exceptions catcher listener: catch kernel.exception event (exception: %s)', $event->getException()->getMessage())); // If this is not a master request, skip handling if (!$event->isMasterRequest()) { $this->logger->debug('Exceptions catcher listener: this is not master request, skip'); return; } // If content already prepared if ($event->hasResponse()) { $this->logger->debug('Exceptions catcher listener: event already has response, skip'); return; } // Getting action $apiServerAction = $event->getRequest()->attributes->get('apiAction'); /* @var $apiServerAction ApiServerAction */ // Something wrong if (!$apiServerAction) { $this->logger->error('Request parser listener: request has no apiAction attribute, sending empty response'); $event->setResponse(new JsonResponse([])); return; } // Getting api server interface $apiServerInterface = $apiServerAction->getApiServerInterface(); // Creating api response $apiResponse = $apiServerInterface->getExceptionResponse($event->getException()->getMessage()); // Setting response $event->setResponse(new JsonResponse($apiResponse->export())); }
/** * Get database prefix. * * @throws EmptyDatabasePrefixException * @return string */ protected function _getPrefix() { $prefix = $this->_systemconfig->getParameter('mysql.dbprefix'); if (empty($prefix)) { $this->_logger->error('MySQL database prefix not configured.'); throw new EmptyDatabasePrefixException(); } return $prefix; }
/** * @param Customer $customer * @param $password * @return bool */ public function subscribeCustomer(Customer $customer, $password) { $em = $this->entityManager; $galittProvider = $this->galittProvider; $hashPassword = $galittProvider->hashPassword($password); try { $alreadyRegistered = $galittProvider->getCustomer($customer->getEmail()); } catch (\Exception $e) { $this->logger->error(sprintf('An error occured while trying to get a Galitt customer with email (%s) via the getCustomer webservice. Request failed with message : "%s"', $customer->getEmail(), $e->getMessage())); return false; } $accentCards = array(); if ($alreadyRegistered) { try { $passwordGalitt = $galittProvider->getPasswordCustomer($customer->getEmail()); } catch (\Exception $e) { $this->logger->error(sprintf('An error occured while trying to get a password Galitt customer with email (%s) via the getPasswordCustomer webservice. Request failed with message : "%s"', $customer->getEmail(), $e->getMessage())); return false; } if ($passwordGalitt != $hashPassword) { try { if (!$galittProvider->updatePassword($customer->getEmail(), $hashPassword, $passwordGalitt)) { return false; } } catch (\Exception $e) { $this->logger->error(sprintf('An error occured while trying to update a password Galitt customer with parameters (Email : %s, Password : %s, PasswordGalitt : %s) via the updatePassword webservice. Request failed with message : "%s"', $customer->getEmail(), $hashPassword, $passwordGalitt, $e->getMessage())); return false; } } $customer->setPassword(null); $customer->setLoyalty(1); if ($customer->getTempCardNumber()) { $this->addAccentCard($customer, $customer->getTempCardNumber()); $customer->setTempCardNumber(null); } $em->persist($customer); $em->flush(); return true; } else { try { $galittProvider->setAccountFidelity($customer, $password, $customer->getTempCardNumber() ?: null); $customer->setPassword(null); $customer->setLoyalty(1); if ($customer->getTempCardNumber()) { $this->addAccentCard($customer, $customer->getTempCardNumber()); $customer->setTempCardNumber(null); } $em->persist($customer); $em->flush(); return true; } catch (\Exception $e) { $this->logger->error(sprintf('An error occured while trying to create a customer (id : %s, email : %s) account on Galitt via the setAccountFidelity webservice. Request failed with message : "%s"', $customer->getId(), $customer->getEmail(), $e->getMessage())); return false; } } }
/** * @param PostResponseEvent $event */ public function onKernelTerminate(PostResponseEvent $event) { foreach ($this->users as $user) { try { $this->galittProvider->updateAccountFidelity($user); } catch (\Exception $e) { $this->logger->error(sprintf('An error occured while trying to update a customer (id : %s, email : %s) account on Galitt via the updateAccountFidelity webservice. Request failed with message : "%s"', $user->getId(), $user->getEmail(), $e->getMessage())); } } }
/** * Create BranchEmailConfiguration * @param Command\BranchEmailConfigurationCommand $branchEmailConfigurationCommand * @return int * @throws \RuntimeException if unable to load required branch */ public function createBranchEmailConfiguration(Command\BranchEmailConfigurationCommand $branchEmailConfigurationCommand) { $branch = $this->branchRepository->get($branchEmailConfigurationCommand->branch); if (is_null($branch)) { $this->logger->error(sprintf('Failed to load email configuration for branch: %s', $branchEmailConfigurationCommand->branch)); throw new \RuntimeException('Branch Email Configuration loading failed, branch not found.'); } $branchEmailConfiguration = $this->branchEmailConfigurationFactory->create($branch, $branchEmailConfigurationCommand->customerDomains, $branchEmailConfigurationCommand->supportAddress); $this->branchEmailConfigurationRepository->store($branchEmailConfiguration); return $branchEmailConfiguration->getId(); }
public function onKernelView(GetResponseForControllerResultEvent $event) { $this->logger->debug('Response builder listener: catch kernel.request event'); // If this is not a master request, skip handling if (!$event->isMasterRequest()) { $this->logger->debug('Response builder listener: this is not master request, skip'); return; } // If content already prepared if ($event->hasResponse()) { $this->logger->debug('Response builder listener: event already has response, skip'); return; } // Getting controller result $result = $event->getControllerResult(); // If result is Response instance if ($result instanceof Response) { $this->logger->debug('Response builder listener: controller result is already an instance of Response, skip'); return; } // Getting action $apiServerAction = $event->getRequest()->attributes->get('apiAction'); /* @var $apiServerAction ApiServerAction */ // Something wrong if (!$apiServerAction) { $this->logger->error('Response parser listener: request has no apiAction attribute, throwing access denied exception'); throw new AccessDeniedHttpException(); } // Getting api server interface $apiServerInterface = $apiServerAction->getApiServerInterface(); // Getting connection $apiServerConnection = $event->getRequest()->attributes->get('apiConnection'); /* @var $apiServerConnection ApiServerConnection */ // Something wrong if (!$apiServerConnection) { $this->logger->error('Response parser listener: request has no apiConnection attribute, throwing access denied exception'); throw new AccessDeniedHttpException(); } // Creating api response try { $apiResponse = $apiServerInterface->getApiResponse($result); $newApiUserToken = $apiServerConnection->getNewApiUserToken(); if ($newApiUserToken) { $this->logger->debug('Response builder listener: applying new api user token to response'); $apiResponse->setUserToken($newApiUserToken); } } catch (\Exception $e) { $this->logger->error(sprintf('Response parser listener: problem with building response ("%s"), sending exception response', $e->getMessage())); $apiResponse = $apiServerInterface->getExceptionResponse($e->getMessage()); } // Setting response $event->setResponse(new JsonResponse($apiResponse->export())); $this->logger->debug('Response builder listener: response built'); }
/** * @param TokenInterface $token * @return WsseToken|TokenInterface */ public function authenticate(TokenInterface $token) { $user = $this->userProvider->loadUserByUsername($token->getUsername()); if ($user && $this->validateDigest($token->getAttribute('digest'), $token->getAttribute('nonce'), $token->getAttribute('created'), $this->getSecret($user), $this->getSalt($user), $user)) { $authenticatedToken = new WsseToken($user->getRoles()); $authenticatedToken->setUser($user); $authenticatedToken->setAuthenticated(true); return $authenticatedToken; } $this->logger->error(sprintf('Attempt of unauthorized access for user: %s', $token->getUsername())); throw new AuthenticationException(' Incorrect email or password.'); }
/** * Returns current user from session * * @ApiDoc( * description="Get current user", * uri="/users/current.{_format}", * method="GET", * resource=true, * statusCodes={ * 200="Returned when successful", * 401="Returned when the user is not found" * } * ) * @return \Diamante\UserBundle\Model\DiamanteUser */ public function getCurrentUser() { $apiUser = $this->authorizationService->getLoggedUser(); if (!$apiUser instanceof ApiUser) { throw new ForbiddenException('Your session seems to be dirty. Please, log out of Diamante Admin and try again'); } try { $diamanteUser = $this->loadDiamanteUser($apiUser); return $diamanteUser; } catch (\Exception $e) { $this->logger->error('No Diamante User is present for ApiUser provided'); throw new AuthenticationException('Attempt of unauthorized access'); } }
/** * Execute the command. Get all the deposits needing to be harvested. Each * deposit will be passed to the commands processDeposit() function. * * @param InputInterface $input * @param OutputInterface $output */ protected final function execute(InputInterface $input, OutputInterface $output) { $this->preExecute(); $deposits = $this->getDeposits($input->getOption('retry'), $input->getArgument('deposit-id')); if ($input->hasOption('limit')) { $deposits = array_slice($deposits, 0, $input->getOption('limit')); } $count = count($deposits); $this->logger->info("Processing {$count} deposits."); $this->preprocessDeposits($deposits); foreach ($deposits as $deposit) { try { $result = $this->processDeposit($deposit); } catch (Exception $e) { $this->logger->error($e->getMessage()); $deposit->setState($this->errorState()); $deposit->addToProcessingLog($this->failureLogMessage()); $deposit->addErrorLog(get_class($e) . $e->getMessage()); $this->em->flush($deposit); continue; } if ($input->getOption('dry-run')) { continue; } if ($result) { $deposit->setState($this->nextState()); $deposit->addToProcessingLog($this->successLogMessage()); } else { $deposit->setState($this->errorState()); $deposit->addToProcessingLog($this->failureLogMessage()); } $this->em->flush($deposit); } }
/** * Create one new working month, days etc for the production plan. * This function ensures that only one month is created, it prevents * two users from creating the same month: * + throw in code and * + unique dates in the database * * @param \DateTime $scope * @param WorkingMonthRepository $workingMonthRepository * @return null|WorkingMonth */ public function createNewProductionPlan(\DateTime $scope, WorkingMonthRepository $workingMonthRepository) { try { $item = $workingMonthRepository->findWorkingMonthByDate($scope); if (!is_null($item)) { throw new \Exception('working month already exists(' . $scope->format('m.d.Y') . ')'); } $year = $scope->format('Y'); $month = $scope->format('m'); $workingMonth = $this->dispoService->openWorkingMonth($year, $month); return $workingMonth; } catch (\Exception $e) { $this->logger->error('ProductionPlanAssembler->' . 'createNewProductionPlan: ' . $e->getMessage()); return null; } }
public function testCountErrorsWithoutDebugHandler() { $handler = new TestHandler(); $logger = new Logger(__METHOD__, array($handler)); $this->assertTrue($logger->error('error message')); $this->assertSame(0, $logger->countErrors()); }
/** * @param $controllerResult * @return ApiResponse * @throws ApiServerException * @throws \Leoza\EntitiesBundle\EntityManagerException */ public function getApiResponse($controllerResult) { $apiResponse = new ApiResponse(); if ($controllerResult instanceof ApiResponse) { // answer with ready response $apiResponse = $controllerResult; } elseif ($controllerResult === true) { // correct success answer without result entity $apiResponse->setStatus(true); } elseif ($controllerResult instanceof Entity) { // correct success answer with result entity $apiResponse->setStatus(true)->setData($this->entityManager->convertEntityTo($controllerResult, $this->targetName)); } elseif ($controllerResult === false) { // correct fail answer without details $apiResponse->setStatus(false); } elseif (is_array($controllerResult)) { // correct fail answer with errors $apiResponse->setStatus(false)->setErrors($controllerResult); } elseif (is_string($controllerResult)) { // correct fail answer with exception $apiResponse->setStatus(false)->setException($controllerResult); } elseif (is_null($controllerResult)) { $this->logger->error(sprintf('Interface %s: controller returns null', $this->getName())); throw new AccessDeniedHttpException(); } else { $this->logger->error(sprintf('Interface %s: controller returns something strange', $this->getName())); throw new ApiServerException(); } return $apiResponse; }
public function upload(Attachment $attachment) { $file = $attachment->getFile(); $hash = $attachment->getHash(); try { if (!file_exists($file->getPathname()) || !is_readable($file->getPathname())) { throw new \RuntimeException('File does not exist'); } $f = fopen($file->getPathname(), 'rb'); $result = $this->client->uploadFile($this->getDropboxName($file, $hash), \Dropbox\WriteMode::add(), $f); fclose($f); } catch (\Exception $e) { $this->logger->error(sprintf("Failed to upload '%s'. Reason: %s Code: %s", $file->getFilename(), $e->getMessage(), $e->getCode())); throw new \RuntimeException(sprintf("Failed to upload %s.", $file->getFilename())); } return $file->getFilename(); }
public function onZigotooEvent(ZigotooEvent $event) { foreach ($this->emails as $mail) { if ($mail->event() === $event->event()) { try { $swiftMessage = Swift_Message::newInstance()->setSubject($mail->subject($event))->setFrom($mail->from($event))->setTo($mail->to($event))->setBody($this->templating->render($mail->template($event), $mail->context($event)), 'text/plain'); /** @var \Swift_Mime_Message $swiftMessage */ $this->mailer->send($swiftMessage); $this->logger->info('Mail envoyé', ['email' => get_class($mail), 'to' => $mail->to($event), 'from' => $mail->from($event), 'template' => $mail->template($event)]); // @codeCoverageIgnoreStart } catch (Exception $e) { $this->logger->error('Echec d\'envoi de mail', ['email' => get_class($mail), 'to' => $mail->to($event), 'from' => $mail->from($event), 'template' => $mail->template($event), 'exception' => $e]); // @codeCoverageIgnoreEnd } } } }
/** * send file to S3 aws bucket * @param $Path file to upload * @param $aws_key aws target path * @return JsonResponse * @throws * @throws Exception */ public function process($Path, $aws_key) { try { $this->multipartUploader($path, $aws_key); } catch (MultipartUploadException $e) { $this->logger->error('MultiPart Uploader error : ' . $e->getMessage()); return new JsonResponse(['Error' => $e->getMessage(), 'status' => 500], 200); } $webPath = $this->container->getParameter('api.imgix.source') . '/' . $aws_key; return new JsonResponse(['message' => "success", 'status' => 200, 'callback_url' => $webPath, 'resource_id' => $image->getId()], 200); }
/** * @param UploadedFile $file * @param string $clientName * @param string $context * * @return \Avtonom\MediaStorageClientBundle\Entity\ProxyMediaInterface * * @throws MediaStorageClientManagerException * @throws \Avtonom\MediaStorageClientBundle\Exception\MediaStorageClientProxyMediaManagerException */ public function sendFile(UploadedFile $file, $clientName, $context) { try { $response = $this->apiService->sendFile($file, $clientName, $context); } catch (MediaStorageClientApiException $e) { $this->logger->error($e->getMessage()); throw new MediaStorageClientManagerException($e->getMessage()); } if ($response && $response->isOk()) { $content = json_decode($response->getContent(), true); if ($content && !json_last_error() && is_array($content) && array_key_exists('reference_full', $content)) { $proxyMedia = $this->proxyMediaManager->createFromResponse($response); return $proxyMedia; } $this->logger->warning('Client not response new value: ' . $content); throw new MediaStorageClientManagerException('Client not response new value'); } $this->logger->warning('Client response code: ' . $response->getStatusCode() . ' ' . $response->getContent()); throw new MediaStorageClientManagerException('Client response code: ' . $response->getStatusCode()); }
/** * @param ValidationException $e * @param User $user * @param PageAnimal $pageAnimal * @return Response * @throws ValidationException */ private function createValidationErrorResponse(ValidationException $e, User $user, PageAnimal $pageAnimal) { $this->logger->error($e->getMessage(), ['exception' => $e, 'user' => $user, 'pageAnimal' => $pageAnimal]); switch ($e->getCode()) { case ValidationException::EMPTY_NOM: return new Response('L\'animal doit avoir un nom', Response::HTTP_NOT_ACCEPTABLE); case ValidationException::EMPTY_DATE_NAISSANCE: return new Response('L\'animal doit avoir une date de naissance', Response::HTTP_NOT_ACCEPTABLE); } throw $e; // @codeCoverageIgnore }
/** * @param HistoryException $e * @return Response * @throws HistoryException */ private function createErrorResponse(HistoryException $e, User $user, PageEleveur $pageEleveur) { $this->logger->error($e->getMessage(), ['exception' => $e, 'user' => $user, 'pageEleveur' => $pageEleveur]); switch ($e->getCode()) { case HistoryException::NON_FAST_FORWARD: return new Response('Plusieurs éditions sont en cours, veuillez rafraichir la page.', Response::HTTP_CONFLICT); case HistoryException::DROIT_REFUSE: return new Response('Vous ne pouvez pas modifier cette page. Vérifiez que vous êtes bien connecté.', Response::HTTP_FORBIDDEN); case HistoryException::BRANCHE_INCONNUE: return new Response('La page a été supprimée.', Response::HTTP_NOT_FOUND); } throw $e; // @codeCoverageIgnore }
/** * @Route("/", name="teaser_route") * @param Request $request * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response * @throws \Exception */ public function teaserAction(Request $request) { /** @var AnonymousToken $token */ $token = $this->tokenStorage->getToken(); /** @var User $user */ $user = $token->getUser(); if ($user == 'anon.') { return $this->templating->renderResponse('base.html.twig', [TwigNodeTemplateTreeSection::TEMPLATE_TREE_BRANCH => 'home/teaser']); } $pageEleveur = $this->pageEleveurService->findByOwner($user); $form = $this->formFactory->createNamedBuilder('creation-page-eleveur')->add('nom', TextType::class, ['label' => 'Nom de l\'élevage'])->add('save', SubmitType::class, array('label' => 'Créer ma page éleveur'))->getForm(); $form->handleRequest($request); if (!$form->isSubmitted() && $pageEleveur) { // un eleveur ne peux pas créer une 2eme page eleveur return $this->templating->renderResponse('base.html.twig', [TwigNodeTemplateTreeSection::TEMPLATE_TREE_BRANCH => 'home/eleveur', 'pageEleveur' => $pageEleveur]); } if ($form->isSubmitted() && $form->isValid()) { // traitement du formulaire de creation de page eleveur $nom = $form->getData()['nom']; try { $slug = $this->pageEleveurService->create($nom, $user)->getSlug(); return new RedirectResponse($this->router->generate('getPageEleveur_route', ['pageEleveurSlug' => $slug])); } catch (HistoryException $e) { $this->logger->error($e->getMessage(), ['exception' => $e, 'user' => $user, 'nom' => $nom]); switch ($e->getCode()) { case HistoryException::NOM_INVALIDE: return new Response('Le nom "' . $nom . '" n\'est pas valide.', Response::HTTP_NOT_ACCEPTABLE); case HistoryException::SLUG_DEJA_EXISTANT: return new Response('Une page éleveur du même nom existe déjà.', Response::HTTP_CONFLICT); case HistoryException::DEJA_OWNER: return new Response('Vous avez déjà une page éleveur.', Response::HTTP_BAD_REQUEST); } } } // home d'un user connecté mais qui n'a pas de page eleveur return $this->templating->renderResponse('base.html.twig', [TwigNodeTemplateTreeSection::TEMPLATE_TREE_BRANCH => 'home/creation-page-eleveur', 'creationPageEleveur' => $form->createView()]); }
public function apiUserAuthenticated(ApiUserInterface $user) { $this->logger->notice(sprintf('Connection: trying to authenticate user as "%s" [id: %s]', $user->getName(), $user->getId())); if ($this->getApiUser()) { $this->logger->notice(sprintf('Connection: user is already authenticated as "%s" [id: %s]', $this->getApiUser()->getName(), $this->getApiUser()->getId())); throw new ApiServerException('User is already authenticated'); } if (!$user || !$user->getId()) { $this->logger->error('Connection: trying to authenticate with undefined user'); throw new ApiServerException('Trying to authenticate with undefined user'); } $this->apiUser = $user; $this->logger->notice('Connection: user authenticated'); $this->generateNewApiUserToken(); }
/** * Grant permissions on database for MySQL User * * @param MysqlDatabaseModel $database * * @return bool * @throws DatabaseNotExistsException */ public function grantPermissionsOnDatabase(MysqlDatabaseModel $database) { if (!$this->checkDatabaseExists($database)) { $this->_logger->error('MySQL Database not exists: ' . $database->getName()); throw new DatabaseNotExistsException(); } foreach ($database->getUsers() as $user) { $q = sprintf('GRANT %s ON %s.* TO "%s"@"%s"', join(', ', $database->getPermission()), $database->getName(), $user->getUsername(), $user->getHost()); $result = $this->_mysqli->query($q); if (!$result) { $this->_logger->error('Could not grant permissions on MySQL database: ' . $database->getName()); } } $this->_logger->info('Granted permissions on MySQL database: ' . $database->getName()); return true; }
/** * @param \Diamante\DeskBundle\Model\Attachment\File $file * @param $hash * @param $fileNamePrefix * @return \Imagine\Image\ManipulatorInterface */ public function createThumbnail(File $file, $hash, $fileNamePrefix) { $image = $this->loader->getImagine()->open($file->getPathname()); $thumbnail = $image->thumbnail(new Box(100, 100)); $destinationFolder = sprintf('%s/thumbnails', $this->getDestination($fileNamePrefix)); try { if (!file_exists($destinationFolder)) { mkdir($destinationFolder); chmod($destinationFolder, 0777); } $destination = sprintf("%s/%s.%s", $destinationFolder, $hash, self::DEFAULT_THUMB_EXT); $thumbnail->save($destination); } catch (\Exception $e) { $this->logger->error(sprintf('Attachment directory is not accessible! Reason: %s', $e->getMessage())); throw new \RuntimeException('Thumbnail could not be created. ' . $e->getMessage()); } }
/** ------------------------- * Register one driving order (one way: outbound or return) * * @param DrivingOrderRegisterDTO $registerDTO * @param Passenger $passenger * @param $direction * @param mixed $status * @param array $errors * @return DrivingOrder|null * @throws Exception */ protected function registerDtoToDrivingOrder(DrivingOrderRegisterDTO $registerDTO, Passenger $passenger, $direction, $status, &$errors) { /** @var Address $fromAddress */ $fromAddress = $this->addressAssembler->addressLookaheadDTOtoAddress($registerDTO->lookaheadaddressFrom); /** @var Address $toAddress */ $toAddress = $this->addressAssembler->addressLookaheadDTOtoAddress($registerDTO->lookaheadaddressTo); if ($fromAddress->getId() === $toAddress->getId() or null === $fromAddress or null === $toAddress) { $errors[] = 'drivingorder.form.error.illegalRoute'; return null; } /** @var Zone $zone */ $zone = $this->zonePlanManagement->getZoneWithHighestPriorityForCities(array($fromAddress->getCity(), $toAddress->getCity())); if (null == $zone) { $errors[] = 'drivingorder.form.error.zone'; return null; } /** @var Route $route */ $route = null; $pickupTime = null; try { if ($direction === self::OUTWARD_DIRECTION) { $pickupTime = $registerDTO->orderTime->outwardTime; $route = $this->routeManagement->getRouteFromAddresses($fromAddress, $toAddress); } elseif ($direction === self::RETURN_DIRECTION) { $pickupTime = $registerDTO->orderTime->returnTime; $route = $this->routeManagement->getRouteFromAddresses($toAddress, $fromAddress); } else { $errors[] = 'drivingorder.form.error.unknown'; } } catch (Exception $e) { $errors[] = 'drivingorder.form.error.routingError'; return null; } if (null === $route or null === $pickupTime) { $errors[] = 'drivingorder.form.error.routingError'; $this->logger->error('Driving order: routing error (' . "Direction => {$direction}, " . "From => " . $fromAddress->getStreet() . ' ' . $fromAddress->getCity() . ', ' . "To => " . $toAddress->getStreet() . ', ' . $toAddress->getCity() . ')'); return null; } else { $drivingOrder = DrivingOrder::registerDrivingOrder($passenger, $registerDTO->anchorDate, $pickupTime, $registerDTO->compagnion, $registerDTO->memo, $status, false, $registerDTO->additionalTime); $drivingOrder->assignRoute($route); $drivingOrder->assignZone($zone); $passenger->assignDrivingOrder($drivingOrder); return $drivingOrder; } return null; }
/** * @internal */ public function saveExchangeRates($force = false, array $currencyRates = array()) { $this->logger->info(sprintf('[|%s] Rates sync is started.', Utils::getClassBasename($this))); if (!empty($currencyRates)) { $this->currencyRates = $currencyRates; } if (!empty($this->currencyRates)) { try { // Iterate the currencies foreach ($this->currencyRates as $currencyCode => $dates) { $lastDateObj = new \DateTime(key($dates)); $lastRateValue = current($dates); // Iterate the date and rate foreach ($dates as $date => $value) { $dateObj = new \DateTime($date); // Persist rates for date differences between current and last date (weekend) $interval = date_diff($lastDateObj, $dateObj); $this->setMissingRatesAndPersist($lastDateObj, $interval->format('%d') - 1, $currencyCode, $lastRateValue, $force); // Persist the current rate $rate = $this->createOrUpdateRate($currencyCode, $value, $dateObj, $force); if (null !== $rate) { $this->em->persist($rate); } $lastDateObj = clone $dateObj; $lastRateValue = $value; } // Insert difference of last MNB date and tomorrow using last MNB rate $tomorrow = new \DateTime('tomorrow'); $difference = $tomorrow->diff($lastDateObj); $this->setMissingRatesAndPersist($lastDateObj, $difference->format('%d'), $currencyCode, $value, $force); } $this->em->flush(); $this->logger->info(sprintf('[|%s] Rates synced successfully.', Utils::getClassBasename($this))); } catch (Exception $exc) { $this->logger->error(sprintf('[|%s] Rates synced FAILED! Error message: ' . $exc->getTraceAsString(), Utils::getClassBasename($this))); } return true; } else { $this->logger->alert(sprintf('[|%s] The currency rates array is empty.', Utils::getClassBasename($this))); return false; } $this->logger->info(sprintf('[|%s] Rates sync is ended.', Utils::getClassBasename($this))); }
private function authenticate() { $this->logger->debug('SecurityManager: authentication and identifying'); // Reset variables $this->user = null; $this->userCard = null; // If no token set... let's get card information from session if (!$this->apiClient->isUserTokenSet()) { $this->logger->debug('SecurityManager: no token set'); return $this->loadUserCardFromSession(); } // Token set, ok $now = new \DateTime(); $userDataExpiresAt = $this->getSession()->get('leoza_api_server.security.userDataExpiresAt'); // If no user data expire information if (!$userDataExpiresAt) { $this->logger->debug('SecurityManager: no expiration info in the session'); return $this->authenticateUserWithUpdateOrLoadUserCardFromSession(); } // We have an expire info $userDataExpiresAt = new \DateTime($userDataExpiresAt); $isExpired = $userDataExpiresAt < $now; // If this info is expired if ($isExpired) { $this->logger->debug('SecurityManager: session info has expired'); return $this->authenticateUserWithUpdateOrLoadUserCardFromSession(); } // Cool, info is actual $userData = $this->getSession()->get('leoza_api_server.security.userData'); $user = $userData ? new $this->userClass($userData) : null; /* @var $user UserInterface */ // If info is invalid... if (!$user || !$user->getId()) { $this->logger->error('SecurityManager: session info is invalid'); return $this->authenticateUserWithUpdateOrLoadUserCardFromSession(); } // Yeah! $this->user = $user; $this->userCard = new $this->userCardClass($this->user); $this->logger->debug(sprintf('SecurityManager: user authenticated as %s [id: %d] using session info', $this->user->getName(), $this->user->getId())); return true; }
/** * Creates Comment for Ticket * * @param $content * @param $authorId * @param $messageId * @param array|null $attachments * @return Ticket|null */ public function createCommentForTicket($content, $authorId, $messageId, array $attachments = null) { if (empty($content)) { return null; } $reference = $this->messageReferenceRepository->getReferenceByMessageId($messageId); if (is_null($reference)) { $this->logger->error(sprintf('Ticket not found for message: %s', $messageId)); throw new \RuntimeException('Ticket loading failed, ticket not found.'); } $ticket = $reference->getTicket(); $command = new CommentCommand(); $command->ticket = $ticket->getId(); $command->content = $content; $command->author = User::fromString($authorId); $command->ticketStatus = $ticket->getStatus(); $command->attachmentsInput = $this->convertAttachments($attachments); $this->commentService->postNewCommentForTicket($command); return $ticket; }
/** * Creates Comment for Ticket * * @param $content * @param $authorId * @param $messageId * @param array $attachments * @return Ticket|null */ public function createCommentForTicket($content, $authorId, $messageId, array $attachments = null) { $reference = $this->messageReferenceRepository->getReferenceByMessageId($messageId); if (is_null($reference)) { $this->logger->error(sprintf('Ticket not found for message: %s', $messageId)); throw new \RuntimeException('Ticket loading failed, ticket not found.'); } $ticket = $reference->getTicket(); $author = User::fromString($authorId); if (empty($content)) { return null; } $comment = $this->commentFactory->create($content, $ticket, $author); if ($attachments) { $this->createAttachments($attachments, $comment); } $ticket->postNewComment($comment); $this->ticketRepository->store($ticket); $this->dispatchEvents($ticket); return $ticket; }
public function testCountErrorsWithDebugProcessor() { $handler = new TestHandler(); $processor = new DebugProcessor(); $logger = new Logger(__METHOD__, array($handler), array($processor)); $this->assertTrue($logger->debug('test message')); $this->assertTrue($logger->info('test message')); $this->assertTrue($logger->notice('test message')); $this->assertTrue($logger->warning('test message')); $this->assertTrue($logger->error('test message')); $this->assertTrue($logger->critical('test message')); $this->assertTrue($logger->alert('test message')); $this->assertTrue($logger->emergency('test message')); $this->assertSame(4, $logger->countErrors()); }