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()));
 }
 /**
  * Executes installation of all Diamante bundles
  * @param InputInterface  $input  An InputInterface instance
  * @param OutputInterface $output An OutputInterface instance
  *
  * @return null|integer null or 0 if everything went fine, or an error code
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->logger->info(sprintf('DiamanteDesk installation started at %s', date('Y-m-d H:i:s')));
     $forceInstall = $input->getOption('force');
     // if there is application is not installed or no --force option
     $isInstalled = $this->getContainer()->hasParameter('installed') && $this->getContainer()->getParameter('installed');
     if ($isInstalled && !$forceInstall) {
         return $this->alreadyInstalledMessage($output);
     }
     if ($forceInstall) {
         // if --force option we have to clear cache and set installed to false
         $this->updateInstalledFlag(false);
         $this->commandExecutor->runCommand('cache:clear', ['--no-optional-warmers' => true, '--process-isolation' => true]);
     }
     $output->writeln('<info>Installing DiamanteDesk.</info>');
     $this->checkRequirementsStep($output);
     $this->prepareStep($this->commandExecutor, $input->getOption('drop-database'))->loadDataStep($this->commandExecutor, $output);
     $output->writeln('<info>Administration setup.</info>');
     $this->finalStep($this->commandExecutor, $output, $input);
     $output->writeln(sprintf('<info>DiamanteDesk has been successfully installed in <comment>%s</comment> mode.</info>', $input->getOption('env')));
     if ('prod' != $input->getOption('env')) {
         $output->writeln('<info>To run application in <comment>prod</comment> mode, ' . 'please run <comment>cache:clear</comment> command with <comment>--env prod</comment> parameter</info>');
     }
     $this->logger->info(sprintf('DiamanteDesk installation finished at %s', date('Y-m-d H:i:s')));
     return 0;
 }
 private function configure($controllersNamespace, $defaultController, $defaultAction, $requestAction)
 {
     // checking base controller namespace
     if (!$controllersNamespace) {
         $this->logger->critical('Action: interface namespace is not configured');
         throw new ApiServerException(sprintf('Action of interface "%s" error: controllers namespace not configured', $this->getInterfaceName()));
     }
     // reset variables
     $path = [];
     $controller = null;
     $action = null;
     // parsing request action
     $requestAction = str_replace(['/', '\\'], ':', $requestAction);
     $requestAction = trim($requestAction, ':');
     if ($requestAction) {
         $requestActionParts = explode(':', $requestAction);
         if (count($requestActionParts) < 2) {
             $controller = ucfirst($requestActionParts[0]);
         } else {
             $action = lcfirst(array_pop($requestActionParts));
             $controller = ucfirst(array_pop($requestActionParts));
             $path = $requestActionParts;
         }
     }
     if (!$controller) {
         $controller = ucfirst($defaultController);
     }
     if (!$action) {
         $action = lcfirst($defaultAction);
     }
     if (!$controller || !$action) {
         $this->logger->notice(sprintf('Action: unable to route action "%s"', $requestAction));
         throw new ApiServerException(sprintf('Action of interface "%s" error: unable to route action "%s"', $this->getInterfaceName(), $requestAction));
     }
     foreach ($path as &$subPath) {
         $subPath = ucfirst($subPath);
     }
     // calculating local class name
     $localClassName = $path;
     array_unshift($localClassName, 'Request');
     array_push($localClassName, $controller);
     array_push($localClassName, ucfirst($action) . 'Data');
     $this->localClassName = implode('\\', $localClassName);
     // calculating controller class name, method and symfony action route
     $controllerClassName = $path;
     array_unshift($controllerClassName, Standard::normalizeNamespace($controllersNamespace));
     array_push($controllerClassName, $controller . 'Controller');
     $controllerClassName = implode('\\', $controllerClassName);
     if (!class_exists($controllerClassName)) {
         $this->logger->notice(sprintf('Action: unable to route action "%s" because class "%s" not exists', $requestAction, $controllerClassName));
         throw new ApiServerException(sprintf('Action of interface "%s" error: unable to find "%s" class', $this->getInterfaceName(), $controllerClassName));
     }
     $controllerMethodName = $action . 'Action';
     if (!method_exists($controllerClassName, $controllerMethodName)) {
         $this->logger->notice(sprintf('Action: unable to route action "%s" because class "%s" does not has method "%s"', $requestAction, $controllerClassName, $controllerMethodName));
         throw new ApiServerException(sprintf('Action of interface "%s" error: controller "%s" has no method "%s"', $this->getInterfaceName(), $controllerClassName, $controllerMethodName));
     }
     $this->actionRoute = $controllerClassName . '::' . $controllerMethodName;
     $this->logger->debug(sprintf('Action: route set to "%s"', $this->actionRoute));
 }
示例#4
0
 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()));
     }
 }
 /**
  * @param $action
  * @param \Doctrine\ORM\Mapping\ClassMetadata $meta
  * @param $entity
  */
 private function logEntityChange($action, \Doctrine\ORM\Mapping\ClassMetadata $meta, $entity)
 {
     $userToken = $this->container->get('security.context')->getToken();
     if (null !== $userToken) {
         $this->logger->info('Entity "' . $meta->getTableName() . '" with id: ' . $meta->getFieldValue($entity, $meta->getSingleIdentifierFieldName()) . ' ' . $action . ' by: ' . $this->container->get('security.context')->getToken()->getUsername());
     }
 }
示例#6
0
 /**
  * @param \Doctrine\Bundle\DoctrineBundle\Registry $doctrine
  * @param \Symfony\Bridge\Monolog\Logger           $logger
  */
 public function __construct(Doctrine $doctrine, Logger $logger)
 {
     $this->entityManager = $doctrine->getManager();
     $dLogger = new \Doctrine\DBAL\Logging\DebugStack();
     $doctrine->getConnection()->getConfiguration()->setSQLLogger($dLogger);
     $logger->info(json_encode($dLogger->queries));
 }
示例#7
0
 public function testCountErrorsWithoutDebugHandler()
 {
     $handler = new TestHandler();
     $logger = new Logger(__METHOD__, array($handler));
     $this->assertTrue($logger->error('error message'));
     $this->assertSame(0, $logger->countErrors());
 }
示例#8
0
 /**
  * @param array $data
  *
  * @return array|string|null
  *
  * @throws \Exception
  */
 public function send($data = null)
 {
     $request = new FormRequest($this->method, $this->resource, $this->host);
     if ($data) {
         $request->addFields($data);
     }
     try {
         $this->logger->addDebug('Request: ' . $request->getUrl());
         /** @var Buzz\Message\Response $response */
         $response = $this->client->send($request);
         $this->logger->addDebug('Response: ' . $response->getStatusCode() . ' ' . substr($response->getContent(), 0, 300) . PHP_EOL . var_export($this->client->getClient()->getInfo(), true));
     } catch (\Exception $e) {
         switch ($e->getCode()) {
             case 28:
                 $code = 504;
                 break;
             default:
                 $code = $e->getCode() >= 100 ? $e->getCode() : 500;
         }
         $this->logger->addCritical(PHP_EOL . __METHOD__ . sprintf('[%s/%s] %s', $e->getCode(), $code, $e->getMessage()));
         throw new WebGateException($e->getMessage(), $code, $e);
     }
     if ($response->getStatusCode() != 200) {
         throw new WebGateException(json_decode($response->getContent(), true), $response->getStatusCode());
     }
     return json_decode($response->getContent(), true);
 }
示例#9
0
 /**
  * @return Logger
  */
 public function getLogger()
 {
     if (null === $this->logger) {
         $this->logger = new Logger(get_called_class());
         $this->logger->pushHandler(new NullHandler());
     }
     return $this->logger;
 }
 /**
  * @param $interfaceName
  * @return ApiServerInterface
  * @throws ApiServerException
  */
 public function buildInterface($interfaceName)
 {
     if (!array_key_exists($interfaceName, $this->config)) {
         $this->logger->critical(sprintf('Interface factory: no config for interface "%s"', $interfaceName));
         throw new ApiServerException(sprintf('Unable to build interface "%s": no config', $interfaceName));
     }
     return new ApiServerInterface($this->container, $this->entityManager, $this->logger, $interfaceName, $this->config[$interfaceName]);
 }
 public function testCountErrorsWithoutDebugHandler()
 {
     $logger = new Logger('test');
     $logger->pushHandler(new TestHandler());
     $logger->addInfo('test');
     $logger->addError('uh-oh');
     $this->assertEquals(0, $logger->countErrors());
 }
示例#12
0
 /**
  * @Route("/sitemap.xml", name="sitemap_route", defaults={"_format"="xml"})
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getSitemapAction()
 {
     /** @var PageEleveurBranch[] $pageEleveurBranchess */
     $pageEleveurBranches = $this->peBranchRepository->findAll();
     $this->logger->info('generation de la sitemap', ['count' => count($pageEleveurBranches)]);
     $this->logger->debug('contenu de la sitemap', ['pageEleveurBranches' => $pageEleveurBranches]);
     return $this->templating->renderResponse('sitemap.xml.twig', ['pageEleveurBranches' => $pageEleveurBranches]);
 }
示例#13
0
 /**
  * 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;
 }
示例#14
0
 public function redirect($path, $route, $scheme = null, $logPath = null)
 {
     if ($logPath) {
         $logger = new Logger('redirect');
         $logger->pushHandler(new StreamHandler($logPath, Logger::INFO));
         $logger->addInfo('redirect', ['url' => $this->context->getPathInfo() . '?' . $this->context->getQueryString(), 'location' => $path, 'method' => $this->context->getMethod()]);
     }
     return parent::redirect($path, $route, $scheme);
 }
示例#15
0
 /**
  * @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;
         }
     }
 }
 public function subscribeNewsletter()
 {
     $errors = $this->validator->validate($this->blaster);
     if (count($errors) > 0) {
         //some errors found, log the errors
         $this->logger->addError((string) $errors);
     }
     $this->em->persist($this->blaster);
     $this->em->flush();
 }
示例#17
0
 public function onCorrectedEvent(CorrectedEvent $event)
 {
     $test = $event->getTest();
     $mail = $this->generateMail($test, "CorrigeatonMailerBundle:Mail:mail-corrected.html.twig", $test->getClassroomsEmails());
     if ($this->mailer->send($mail) == 1) {
         $this->log->addInfo("Mail send : " . $test);
     } else {
         $this->log->addError("Error in send mail : " . $test);
     }
 }
示例#18
0
 /**
  * @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()));
         }
     }
 }
示例#19
0
 protected function initialize(InputInterface $input, OutputInterface $output)
 {
     $this->logger = new Logger($this->getName());
     $this->logger->pushHandler(new ConsoleHandler($output));
     $this->logger->pushProcessor(new MemoryPeakUsageProcessor());
     if (!empty($this->getConfig()->getLogFilename())) {
         $this->logger->pushHandler(new StreamHandler($this->getConfig()->getLogFilename()));
     }
     $this->symfonyStyle = new SymfonyStyle($input, $output);
     $this->getLogger()->debug('Config file', ['file' => $this->getApplication()->getConfigDefaultPath()]);
 }
示例#20
0
 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');
 }
 /**
  * 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();
 }
 /**
  * @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.');
 }
示例#23
0
 public function record(Contact $contact)
 {
     $this->entityManager->persist($contact);
     $this->entityManager->flush();
     try {
         $this->eventDispatcher->dispatch(ZigotooEvent::CONTACT, new ContactEvent($contact));
         // @codeCoverageIgnoreStart
     } catch (Exception $e) {
         $this->logger->critical('', ['exception' => $e, 'contact' => $contact]);
     }
     // @codeCoverageIgnoreEnd
 }
 /**
  * @param PaymentMethodInterface $method
  * @param integer $amount
  *
  * @throws PaymentException
  */
 public function processPayment(PaymentMethodInterface $method, $amount)
 {
     /**
      * @var AdyenMethod $method
      */
     $paymentData = [];
     $paymentData['additionalData'] = ['card.encrypted.json' => $method->getAdditionalData()];
     $paymentData['amount'] = ['value' => $amount, 'currency' => $this->currency];
     $paymentData['reference'] = $method->getTransactionId();
     $paymentData['merchantAccount'] = $this->merchantCode;
     try {
         $r = $this->callApi($paymentData);
     } catch (\Exception $e) {
         /*
          * The Soap call failed
          */
         $this->eventDispatcher->notifyPaymentOrderFail($this->paymentBridge, $method);
         $this->logger->addError('PaymentException: ' . $e->getMessage());
         $this->paymentBridge->setError($e->getMessage());
         $this->paymentBridge->setErrorCode($e->getCode());
         throw new PaymentException($e->getMessage());
     }
     $r['amount'] = $amount;
     $this->storeTransaction($r);
     if (!$this->isAuthorized($r)) {
         $this->paymentBridge->setError($this->getError($r));
         $this->paymentBridge->setErrorCode($this->getErrorCode($r));
         /**
          * The payment was not successful
          */
         $this->eventDispatcher->notifyPaymentOrderFail($this->paymentBridge, $method);
         throw new PaymentException($this->getErrorCode($r));
     }
     $this->eventDispatcher->notifyPaymentOrderLoad($this->paymentBridge, $method);
     /*
      * Everything is ok, emitting the
      * payment.order.create event
      */
     $method->setTransactionId($r['pspReference'])->setTransactionStatus('paid');
     $this->eventDispatcher->notifyPaymentOrderCreated($this->paymentBridge, $method);
     /**
      * Payment process has returned control
      */
     $this->eventDispatcher->notifyPaymentOrderDone($this->paymentBridge, $method);
     /**
      * Payment paid successfully
      *
      * Paid process has ended successfully
      */
     $this->eventDispatcher->notifyPaymentOrderSuccess($this->paymentBridge, $method);
 }
示例#25
0
 /**
  * Send one or more flash messages to the GUI (alerted in next page).
  * Each message is also logged as INFO (with username) for future reference.
  *
  * @param array $messages a number of clear text information messages
  */
 public function handleMessages(array $messages)
 {
     /** @var User $user */
     $user = $this->container->get('security.context')->getToken()->getUser();
     $username = $user->getUsername();
     $messageText = '';
     foreach ($messages as $message) {
         $this->logger->addInfo("Flash Message({$username}):" . $message);
         $messageText .= $message . "\n";
     }
     if ($messageText !== '') {
         $this->container->get('session')->getFlashBag()->add('notice', $messageText);
     }
 }
 /**
  * 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');
     }
 }
 /**
  * Executes installation of all Diamante bundles
  * @param InputInterface  $input  An InputInterface instance
  * @param OutputInterface $output An OutputInterface instance
  *
  * @return null|integer null or 0 if everything went fine, or an error code
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->logger = $this->getContainer()->get('monolog.logger.diamante');
     $this->logger->info(sprintf('DiamanteDesk installation started at %s', date('Y-m-d H:i:s')));
     $this->inputOptionProvider = new InputOptionProvider($output, $input, $this->getHelperSet()->get('dialog'));
     if (false === $input->isInteractive()) {
         $this->validate($input);
     }
     $forceInstall = $input->getOption('force');
     $commandExecutor = $this->getCommandExecutor($input, $output);
     // if there is application is not installed or no --force option
     $isInstalled = $this->getContainer()->hasParameter('installed') && $this->getContainer()->getParameter('installed');
     if ($isInstalled && !$forceInstall) {
         $output->writeln('<comment>ATTENTION</comment>: DiamanteDesk already installed.');
         $output->writeln('To proceed with install - run command with <info>--force</info> option:');
         $output->writeln(sprintf('    <info>%s --force</info>', $this->getName()));
         $output->writeln('To reinstall over existing database - run command with <info>--force --drop-database</info> options:');
         $output->writeln(sprintf('    <info>%s --force --drop-database</info>', $this->getName()));
         $output->writeln('<comment>ATTENTION</comment>: All data will be lost. ' . 'Database backup is highly recommended before executing this command.');
         $output->writeln('');
         return 255;
     }
     if ($forceInstall) {
         // if --force option we have to clear cache and set installed to false
         $this->updateInstalledFlag(false);
         $commandExecutor->runCommand('cache:clear', ['--no-optional-warmers' => true, '--process-isolation' => true]);
     }
     $output->writeln('<info>Installing DiamanteDesk.</info>');
     $this->checkRequirementsStep($output);
     $this->prepareStep($commandExecutor, $input->getOption('drop-database'));
     // load data step
     $output->writeln('<info>Setting up database.</info>');
     $commandExecutor->runCommand('oro:migration:load', ['--force' => true, '--process-isolation' => true, '--exclude' => array('DiamanteEmbeddedFormBundle', 'DiamanteDeskBundle'), '--timeout' => $commandExecutor->getDefaultOption('process-timeout')]);
     $commandExecutor->runCommand('oro:workflow:definitions:load', ['--process-isolation' => true])->runCommand('oro:process:configuration:load', ['--process-isolation' => true])->runCommand('diamante:user:schema', ['--process-isolation' => true])->runCommand('diamante:desk:schema', ['--process-isolation' => true])->runCommand('oro:migration:load', ['--force' => true, '--process-isolation' => true, '--bundles' => ['DiamanteDeskBundle'], '--timeout' => $commandExecutor->getDefaultOption('process-timeout')])->runCommand('diamante:embeddedform:schema', ['--process-isolation' => true]);
     $commandExecutor->runCommand('oro:migration:data:load', ['--process-isolation' => true, '--no-interaction' => true]);
     $commandExecutor->runCommand('diamante:desk:data', ['--process-isolation' => true]);
     $output->writeln('');
     $output->writeln('<info>Administration setup.</info>');
     $this->updateSystemSettings();
     $this->updateOrganization($commandExecutor);
     $this->updateUser($commandExecutor);
     $this->finalStep($commandExecutor, $output, $input);
     $output->writeln(sprintf('<info>DiamanteDesk has been successfully installed in <comment>%s</comment> mode.</info>', $input->getOption('env')));
     if ('prod' != $input->getOption('env')) {
         $output->writeln('<info>To run application in <comment>prod</comment> mode, ' . 'please run <comment>cache:clear</comment> command with <comment>--env prod</comment> parameter</info>');
     }
     $this->logger->info(sprintf('DiamanteDesk installation finished at %s', date('Y-m-d H:i:s')));
     return 0;
 }
 /**
  * Méthode d'envoie d'email
  *
  * @param array $data
  * @param array|array<UserInterface> $aEmailTo
  * @param array $aAttachement
  */
 protected function send($data, $aEmailTo, $aAttachement = array(), MailParametersInterface $mailParameters)
 {
     $mailerForSend = $this->mailer;
     foreach ($aEmailTo as $user) {
         //Create the message
         /* @var $message \Swift_Message */
         $message = \Swift_Message::newInstance()->setSubject($data['objet'])->setFrom(array($this->config['from_email']['address'] => $this->config['from_email']['sender_name']));
         foreach ($aAttachement as $oneAttachment) {
             $attachment = \Swift_Attachment::newInstance($oneAttachment['content'], $oneAttachment['name'], $oneAttachment['type']);
             $message->attach($attachment);
         }
         $failedRecipients = array();
         $numSent = 0;
         if (is_object($user) && method_exists($user, 'getEmail')) {
             $message->setTo($user->getEmail());
         } elseif (is_string($user)) {
             $message->setTo($user);
         } else {
             throw new \RuntimeException('Invalid email');
         }
         $message->setBody($this->templating->render($this->getTemplateDirectory($mailParameters) . ':Mails:' . $data['template'] . '.html.twig', $data), "text/html");
         $message->addPart($this->templating->render($this->getTemplateDirectory($mailParameters) . ':Mails:' . $data['template'] . '.txt.twig', $this->getRaw($data)), "text/plain");
         $numSent += $mailerForSend->send($message, $failedRecipients);
         if ($this->logger && $this->config['active_log'] === true) {
             $this->logger->info(sprintf("Email: '%s' sended to: '%s'", $data['objet'], current(array_keys($message->getTo()))), array('CnertaMailingBundle', 'email-sended'));
         }
     }
     return $numSent;
 }
 /**
  * @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;
 }
示例#30
0
文件: Image.php 项目: fire1/liby
 /**
  * Creates copy of image
  * @param $copyFile
  * @param $dir
  */
 protected function triggerCopy($copyFile, $dir)
 {
     $this->lg->info(sprintf("Executing copy in '%s' destination.", $copyFile));
     $filename = $this->filename(0, $copyFile, false);
     $this->fs->copy($copyFile, $dir . $filename);
     $this->setFilePath(0, $dir, $filename);
 }