zend-blog-3-backend

Форк
0
83 строки · 2.2 Кб
1
<?php
2

3
namespace App\Command;
4

5
use App\Cron\CronChain;
6
use App\Cron\CronServiceInterface;
7
use Symfony\Component\Console\Command\Command;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Xelbot\Telegram\Robot;
11

12
abstract class CronCommand extends Command
13
{
14
    /**
15
     * @return CronServiceInterface[]
16
     */
17
    abstract protected function getCrons(): array;
18

19
    /**
20
     * @var CronChain
21
     */
22
    protected CronChain $chain;
23

24
    /**
25
     * @var Robot
26
     */
27
    private Robot $bot;
28

29
    /**
30
     * @param CronChain $chain
31
     * @param Robot $bot
32
     */
33
    public function __construct(CronChain $chain, Robot $bot)
34
    {
35
        parent::__construct();
36

37
        $this->chain = $chain;
38
        $this->bot = $bot;
39
    }
40

41
    public function execute(InputInterface $input, OutputInterface $output): int
42
    {
43
        $messages = [];
44
        foreach ($this->getCrons() as $cronJob) {
45
            try {
46
                $cronJob->run();
47
                if ($cronJob->getMessage()) {
48
                    $messages[] = sprintf('%s: %s', self::getJobName($cronJob), $cronJob->getMessage());
49
                    $output->writeln(
50
                        sprintf('<comment>%s:</comment> %s', self::getJobName($cronJob), $cronJob->getMessage())
51
                    );
52
                } else {
53
                    $output->writeln(
54
                        sprintf('<comment>%s:</comment> without message', self::getJobName($cronJob))
55
                    );
56
                }
57
            } catch (\Exception $e) {
58
                $messages[] = sprintf('Error %s: %s', self::getJobName($cronJob), $e->getMessage());
59
                $output->writeln(
60
                    sprintf('<error>%s Error:</error> %s', self::getJobName($cronJob), $e->getMessage())
61
                );
62
            }
63
        }
64

65
        if (count($messages)) {
66
            $this->bot->sendMessage(implode("\n", $messages));
67
        }
68

69
        return 0;
70
    }
71

72
    /**
73
     * @param $cronJob
74
     *
75
     * @return string
76
     */
77
    protected static function getJobName($cronJob): string
78
    {
79
        $classParts = explode('\\', get_class($cronJob));
80

81
        return $classParts[count($classParts) - 1];
82
    }
83
}
84

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.