использовать SwiftMailer в команде - Symfon 4.1 - PullRequest
0 голосов
/ 23 сентября 2018

Я создал простую команду, которая берет URL-адрес и проверяет, работает ли веб-сайт, если не отправляет мне электронное письмо, но проблема в том, что я не знаю, как добавить SwiftMailer в команду «Выполнить».

    <?php

namespace App\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use App\Entity\Products;
use App\Entity\Settings;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

class CheckwebsitesCommand extends ContainerAwareCommand
{
    protected static $defaultName = 'checkwebsites';

    protected function configure()
    {
        $this
            ->setName('app:checkwebsites')
            ->setDescription('Add a short description for your command')

        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output, \Swift_Mailer $mailer)
    {

если я добавлю:

protected function execute(InputInterface $input, OutputInterface $output, \Swift_Mailer $mailer)
{

, тогда у меня будет ошибка:

 Warning: Declaration of App\Command\CheckwebsitesCommand::execute(Symfony\Component\Console\Input\InputInterface $input, Symfony\Component\Console\Output\OutputInterface $output, $id)
  should be compatible with Symfony\Component\Console\Command\Command::execute(Symfony\Component\Console\Input\InputInterface $input, Symfony\Component\Console\Output\OutputInterface $ou
  tput)

я могу t understand this "Commands" thing, why i can у просто прикрепить пачки ведьмы, какМне нужно ?Я хочу использовать команды для установки крон.

****** РЕДАКТИРОВАТЬ

   foreach($websites as $website) {
                       $www = $website->getJson();
                       $online = url_test($www['website']['www']);
                       if(!$online) {
                         $message = (new \Swift_Message('Nie działa strona '.$www['website']['www'].' !'))
                         ->setFrom(''.$emailform.'')
                         ->setTo(''.$emailform.'')
                         ->setBody(
                           $this->templating->renderView(
                             'emails/websitenoworking.html.twig',
                             array(
                               'www' => $website['website']['www'],
                             )
                           ),
                           'text/html'
                         );
                         $mailer->send($message);
                       }
                     }

Ответы [ 2 ]

0 голосов
/ 23 сентября 2018

Полная работа:

<?php

namespace App\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use App\Entity\Products;
use App\Entity\Settings;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Twig\Environment;

class CheckwebsitesCommand extends Command
{
      private $entityManager;
      private $mailer;
      private $twig;

      public function __construct(
          EntityManagerInterface $entityManager,
          \Swift_Mailer $mailer,
          Environment $twig
      )
      {
          parent::__construct();
          $this->entityManager = $entityManager;
          $this->mailer = $mailer;
          $this->twig = $twig;
        }
    protected static $defaultName = 'checkwebsites';

    protected function configure()
    {
        $this
            ->setName('app:checkwebsites')
            ->setDescription('Add a short description for your command')

        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);



                    $websites = $this->entityManager
                     ->getRepository(Products::class)
                     ->findBy([
                       'type' => 1,
                     ]);

                     $settings = $this->entityManager
                     ->getRepository(Settings::class)
                     ->findOneBy([
                       'id' => 1,
                     ]);
                     $json = $settings->getJson();
                     foreach($json as $prop) {
                       foreach($prop as $key => $value) {
                         $$key = $value;
                       }
                     }

                      //funkcja sprawdzająca czy strona działa
                      function url_test( $url ) {
                              $timeout = 10;
                              $ch = curl_init();
                              curl_setopt ( $ch, CURLOPT_URL, $url );
                              curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
                              curl_setopt ( $ch, CURLOPT_TIMEOUT, $timeout );
                              $http_respond = curl_exec($ch);
                              $http_respond = trim( strip_tags( $http_respond ) );
                              $http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
                              if ( ( $http_code == "200" ) || ( $http_code == "302" ) ) {
                                return true;
                              } else {
                                // return $http_code;, possible too
                                return false;
                              }
                              curl_close( $ch );
                            }




                     foreach($websites as $website) {
                       $www = $website->getJson();
                       $url = $www['website']['www'];
                       $online = url_test($url);
                       if(!$online) {
                         $message = (new \Swift_Message('Nie działa strona '.$www['website']['www'].' !'))
                         ->setFrom(''.$emailform.'')
                         ->setTo(''.$emailform.'')
                         ->setBody(
                           $this->twig->render(
                             'emails/websitenoworking.html.twig',
                             array(
                               'www' => $url,
                               'firma' => $www,

                             )
                           ),
                           'text/html'
                         );
                         $mailer->send($message);
                       }
                     }


        $io->success('Sprawdzono wszystkie strony.');
    }
}
0 голосов
/ 23 сентября 2018

Просто чтобы немного прокомментировать мой комментарий о внедрении, учитывая, что вы используете S4.1, вам, вероятно, следует также избегать использования ContainerAwareCommand.Использование контейнера в качестве сервисного локатора произошло в прошлом году.Рекомендуется использовать строгое внедрение зависимостей.

namespace App\Command;

use Twig\Environment;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class MailerCommand extends Command
{
    private $entityManager;
    private $mailer;
    private $twig;

    public function __construct(
        EntityManagerInterface $entityManager, 
        \Swift_Mailer $mailer,
        Environment $twig
    )
    {
        parent::__construct();
        $this->entityManager = $entityManager;
        $this->mailer = $mailer;
        $this->twig = $twig;
    }
    protected function configure()
    {
        $this
            ->setName('app:checkwebsites')
            ->setDescription('Add a short description for your command')
        ;
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        echo "Hello there\n";
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...