/** * 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; }
/** * @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()); } }
/** * @return bool */ public function execute($subject) { $this->logger->info('DotpayManager [Response]: ' . json_encode($subject)); $event = new ValidationEvent($subject); $this->dispatcher->dispatch(Events::PRE_VALIDATE, $event); if ($event->isExecuted() && !$event->isValid()) { $this->logger->err('DotpayManager: execution failed during hatimeria_dotpay.pre_validate event'); return false; } $result = $this->validate($subject); if (!$result) { $this->logger->err('DotpayManager: Response validation failed'); return false; } $event = new Event($subject); $this->dispatcher->dispatch(Events::EXECUTION, $event); if (!$event->isExecuted()) { $this->logger->err('DotpayManager: No event found executing payment finalization process'); return false; } if (!$event->getResult()) { $this->logger->err('DotpayManager: hatimeria_dotpay.execution event finished with result false. Check logs for more information'); return false; } return true; }
/** * @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]); }
/** * 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; }
/** * 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); } }
/** * @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)); }
/** * 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); }
/** * 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; }
/** * Find a record in static_page_routes by uri * * @param string $uri * @return StaticPageRoute */ private function matchFromDatabase($uri) { $routeObj = $this->doctrine->getRepository('AdminBundle:StaticPage')->findOneBy(array('url' => $uri)); if ($routeObj) { $this->logger->info("Matched uri '{$uri}' from database"); } return $routeObj; }
/** * Find a record in frontend_routes by uri * * @param string $uri * @return FrontendRoute */ private function matchFromDatabase($uri) { $routeObj = $this->doctrine->getRepository('FrontendBundle:FrontendRoute')->findOneBy(array('uri' => $uri)); if ($routeObj) { $this->logger->info("Matched uri '{$uri}' from database with variables: {$routeObj->getVariables()}"); } return $routeObj; }
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 } } } }
/** * Show DQL in the Firebug / FirePHP console. * * @param string $msg */ private function logDQL($msg) { $this->logger->info($msg . ' query: ' . $this->qb->getQuery()->getDQL()); $params = $this->qb->getQuery()->getParameters(); foreach ($params as $param) { $this->logger->info($msg . ' param name: ' . $param->getName() . ' param value: ' . $param->getValue()); } }
/** * Execute all outstanding updates. */ public function executeUpdates() { try { $providers = $this->_getOutstandingUpdateProviders(); } catch (DBALException $e) { $providers = array(); } catch (\PDOException $e) { $providers = array(); } foreach ($providers as $provider) { $this->_prepareProvider($provider); $this->_logger->info(sprintf('Found update: %s, Ver.: %s', $provider->getName(), $provider->getVersion())); if ($provider->executeUpdate()) { $this->_logger->info(sprintf('Update successful: %s, Ver.: %s', $provider->getName(), $provider->getVersion())); } else { $this->_logger->info(sprintf('Update failed: %s, Ver.: %s', $provider->getName(), $provider->getVersion())); } $this->_saveExecution($provider); } }
private function normalizarNiveles($niveles, $labels) { $result = array(); $nivel_id = 0; foreach ($niveles as $nivel) { $this->logger->info("Nivel: " . $nivel); $entity = is_array($nivel) && isset($nivel['entity']) ? $nivel['entity'] : $nivel; $result[$nivel_id]['entity'] = $entity; $tmpclass = explode(':', $entity); $class = $tmpclass[count($tmpclass) - 1]; $result[$nivel_id]['class'] = $class; $this->logger->info("Class: " . $class); $name = is_array($nivel) && isset($nivel['name']) ? $nivel['name'] : strtolower(substr($class, 0, 1)) . substr($class, 1); $result[$nivel_id]['name'] = $name; if (isset($labels[$nivel_id])) { $result[$nivel_id]['label'] = $labels[$nivel_id]; } $nivel_id++; } return $result; }
public function testCountErrorsWithDebugHandler() { $handler = new DebugHandler(); $logger = new Logger(__METHOD__, array($handler)); $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()); }
/** * 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 Sekolah $sekolah */ public function sendMessage(Sekolah $sekolah = null) { if (!$this->messagePopulated) { $this->populateMessage(); } if ($this->logid == 0) { $this->setLogEntry($sekolah); } $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_URL, $this->messageCommand); $hasil = curl_exec($ch); $this->logger->info($sekolah->getId() . ' | ' . $sekolah->getNama() . ' | ' . $this->messageCommand); $this->updateLogHasilAPI($this->messageCommand, $hasil); curl_close($ch); }
/** * @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))); }
/** * Connect to LDAP service * * @throws InvalidLdapConnectionException, InvalidLdapTlsConnectionException, InvalidLdapBindException */ public function connect() { // Don't permit multiple connect() calls to run if ($this->ldapResource) { return $this->ldapResource; } $this->ldapResource = $this->ldap->connect($this->uri); if ($this->ldapResource === false) { throw new InvalidLdapConnectionException('Unable to enable establish LDAP connection.'); } $this->ldap->setOption($this->ldapResource, LDAP_OPT_PROTOCOL_VERSION, 3); // Switch to TLS, if configured if ($this->useTLS) { if (!$this->ldap->startTls($this->ldapResource)) { throw new InvalidLdapTlsConnectionException('Unable to enable TLS for LDAP connection.'); } $this->logger->info('TLS enabled for LDAP connection.'); } if (!$this->ldap->bind($this->ldapResource, $this->bindDN, $this->password)) { throw new InvalidLdapBindException('Cannot connect to LDAP server: ' . $this->uri . ' as ' . $this->bindDN . '/"' . $this->password . '".'); } $this->logger->debug('Connected to LDAP server: ' . $this->uri . ' as ' . $this->bindDN . ' .'); }
/** * the actual method to process a job. You can override this method in order to define a custom exception-handling * * @param $data mixed the data which is necessary to process the job * @param \Pheanstalk\Job $job * @param \Pheanstalk\Pheanstalk $pheanstalk * @param $tubeIdentifier string the name of the tube * @param \Symfony\Component\Console\Output\OutputInterface $output * @param \Symfony\Bridge\Monolog\Logger $logger */ public function processJob($workload, AbstractDataTransformer $dataTransformer, \Pheanstalk\Job $job, \Pheanstalk\Pheanstalk $pheanstalk, OutputInterface $output, \Symfony\Bridge\Monolog\Logger $logger) { $data = $dataTransformer->wakeupData($workload->data); $tubeIdentifier = $workload->tube; $dispatcher = new EventDispatcher(); try { $this->work($data, $job, $pheanstalk); $pheanstalk->delete($job); $output->writeln(' done!'); $dispatcher->dispatch(PheanstalkEvents::JOB_SUCCEEDED, new JobSuccessEvent($tubeIdentifier)); } catch (NoRetryException $e) { $logger->info('NoRetry Exception: ' . $e->getMessage(), $e->getTrace()); $output->writeln(' Error!'); $output->writeln(sprintf('Worker [%s] failed (no retry) with: %s', $tubeIdentifier, $e->getMessage())); $pheanstalk->delete($job); $dispatcher->dispatch(PheanstalkEvents::JOB_FAILED, new JobFailedEvent($tubeIdentifier, false)); } catch (\Exception $e) { $logger->emerg('Exception ' . get_class($e) . ': ' . $e->getMessage(), $e->getTrace()); $output->writeln(' Error!'); $output->writeln(sprintf('Worker [%s] failed with: %s', $tubeIdentifier, $e->getMessage())); $pheanstalk->release($job, 32768, 60 * 3); $dispatcher->dispatch(PheanstalkEvents::JOB_FAILED, new JobFailedEvent($tubeIdentifier, true)); } }
/** * Gets a language based on the language parameter. Accepts multiple * * @param \Newscoop\Entity\Language|string $language Language which needs to be found * @param \Newscoop\Entity\Language|null $defaultLanguage Fallback language * * @return \Newscoop\Entity\Language|null Returns language entity or null if not found */ private function getLanguage($language, $defaultLanguage = null) { $languageEntity = null; if ($language !== null && $language !== '') { if ($language instanceof \Newscoop\Entity\Language) { $languageEntity = $language; } elseif (strpos($language, '-') !== false && count($language) === 2) { $languageEntity = $this->em->getRepository('\\Newscoop\\Entity\\Language')->findByCode($language); } else { try { $languageEntity = $this->em->getRepository('\\Newscoop\\Entity\\Language')->findByRFC3066bis($language); } catch (Exception $e) { $languageEntity = null; $this->logger->info(__METHOD__ . ': Language for entry could not be found. Reverting to default language.'); } } } // Use default language if no language is set or if the found // languages are not allowed in our selected languages if (!in_array($languageEntity, $this->allowedLanguages)) { $languageEntity = $defaultLanguage; } return $languageEntity; }
private function logInfo($msg) { if ($this->logger) { $this->logger->info($msg); } }
/** * Importe tous les hotels SEH modifiés depuis $sinceDate. * Utilise le webservice Artsys 'flux/modified' pour obtenir la liste des hotels modifiés puis appelle la fonction importAction pour chacun des hotels. * * @param string $sinceDate Date au format YYYY-MM-DD * * @return mixed En mode console retourne une chaine vide, en mode Web retourne un tableau avec les messages à afficher dans le template * * @Route("/modified/{sinceDate}", name="modifiedArtsysHotels") * @Template() */ public function modifiedHotelsAction($sinceDate, $log = false) { if (PHP_SAPI == 'cli') { $this->cli = true; } // Récupération du DataSource $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('BigfootImportBundle:DataSource')->findOneby(array('slug' => $this->container->getParameter('artsys_bundle.datasource_slug'))); // Initialisation du client $detailsClient = new Client(); $detailsClient->init($entity->getProtocol(), $entity->getDomain(), $entity->getPort()); $detailsClient->setAuth($entity->getUsername(), $entity->getPassword()); // Récupération des Ids hotel $xml = $detailsClient->get('flux/modified?since=' . $sinceDate, false); $progress = false; if ($log) { $progressFile = sprintf('%s/../web/uploads/import/progress-%s', $this->get('kernel')->getRootDir(), $sinceDate); if (file_exists($progressFile) and $progress = file_get_contents($progressFile)) { if (strpos($xml, sprintf('codeAdherent="%s"', $progress)) === false) { unlink($progressFile); $progress = false; } } } // Création de l'objet XML $hotels = simplexml_load_string($xml); $nbHotel = count($hotels); if ($nbHotel == 0) { $this->printMessage(sprintf("Aucun hotel modifié depuis le %s.\n", $sinceDate)); } else { $this->printMessage(sprintf("Import de %s hotel(s).\n", $nbHotel)); if ($log) { $this->logger->info(sprintf('>>>> Importing %s hotels (from %s)', $nbHotel, $sinceDate)); } } $averageTime = 0; $nbDone = 0; $import = !$progress; foreach ($hotels as $hotel) { $hotelArtsysId = $hotel->xpath('@codeAdherent'); $hotelArtsysId = (string) $hotelArtsysId[0]; if (!$log or $import or $progress == $hotelArtsysId) { $hotelPath = $hotel->xpath('@codeAdherent'); $codeAdherent = (string) $hotelPath[0]; if ($codeAdherent != "") { try { $this->printMessage(sprintf("Import de l'hôtel avec le code adhérent : %s.\n", $codeAdherent)); $time = microtime(true); $this->importAction($codeAdherent, $log); $time = microtime(true) - $time; $averageTime += $time; if ($log) { $this->logger->info(sprintf('Imported hotel %s (%s / %s) successfully in %s seconds total (%s seconds average total)', $codeAdherent, $nbDone + 1, $nbHotel, $time, $averageTime / ($nbDone + 1))); } } catch (\Exception $e) { $time = microtime(true) - $time; $averageTime += $time; if ($log) { $this->logger->error(sprintf('Error while importing hotel %s (%s) in %s seconds (%s seconds average)', $codeAdherent, $e->getMessage(), $time, $averageTime / ($nbDone + 1))); } $this->printMessage(sprintf("Erreur sur l'import de l'hôtel avec le code adhérent %s.\n", $codeAdherent)); } $nbDone++; } if ($log) { $import = true; if (!file_exists($progressFile)) { $fs = $this->get('filesystem'); $fs->mkdir(dirname($progressFile)); $fs->touch($progressFile); } file_put_contents($progressFile, $hotelArtsysId); } } } if ($log && $nbHotel > 0) { $this->logger->info(sprintf('>>>> Imported %s hotels in %s seconds (average : %s)', $nbHotel, $averageTime, $averageTime / $nbHotel)); unlink($progressFile); } if (!$this->cli) { return array('messages' => $this->messages); } return ""; }
public function handle(RegisterUserCommand $command) { $this->logger->info('register user command recieved!'); }
/** * Add a info in the container. * * @param string $info * * @return PiLogManager * @access public * @author Etienne de Longeaux <*****@*****.**> */ public function setInfo($info) { $this->_info[] = $info; $this->_logger->info($info); return $this; }