zend-blog-3-backend
83 строки · 2.2 Кб
1<?php
2
3namespace App\Command;
4
5use App\Cron\CronChain;
6use App\Cron\CronServiceInterface;
7use Symfony\Component\Console\Command\Command;
8use Symfony\Component\Console\Input\InputInterface;
9use Symfony\Component\Console\Output\OutputInterface;
10use Xelbot\Telegram\Robot;
11
12abstract class CronCommand extends Command
13{
14/**
15* @return CronServiceInterface[]
16*/
17abstract protected function getCrons(): array;
18
19/**
20* @var CronChain
21*/
22protected CronChain $chain;
23
24/**
25* @var Robot
26*/
27private Robot $bot;
28
29/**
30* @param CronChain $chain
31* @param Robot $bot
32*/
33public function __construct(CronChain $chain, Robot $bot)
34{
35parent::__construct();
36
37$this->chain = $chain;
38$this->bot = $bot;
39}
40
41public function execute(InputInterface $input, OutputInterface $output): int
42{
43$messages = [];
44foreach ($this->getCrons() as $cronJob) {
45try {
46$cronJob->run();
47if ($cronJob->getMessage()) {
48$messages[] = sprintf('%s: %s', self::getJobName($cronJob), $cronJob->getMessage());
49$output->writeln(
50sprintf('<comment>%s:</comment> %s', self::getJobName($cronJob), $cronJob->getMessage())
51);
52} else {
53$output->writeln(
54sprintf('<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(
60sprintf('<error>%s Error:</error> %s', self::getJobName($cronJob), $e->getMessage())
61);
62}
63}
64
65if (count($messages)) {
66$this->bot->sendMessage(implode("\n", $messages));
67}
68
69return 0;
70}
71
72/**
73* @param $cronJob
74*
75* @return string
76*/
77protected static function getJobName($cronJob): string
78{
79$classParts = explode('\\', get_class($cronJob));
80
81return $classParts[count($classParts) - 1];
82}
83}
84