Yaffs site version 1.1
[yaffs-website] / vendor / drupal / console-core / src / EventSubscriber / ShowTipsListener.php
1 <?php
2
3 /**
4  * @file
5  * Contains \Drupal\Console\Core\EventSubscriber\ShowTipsListener.
6  */
7
8 namespace Drupal\Console\Core\EventSubscriber;
9
10 use Symfony\Component\Console\ConsoleEvents;
11 use Symfony\Component\Console\Event\ConsoleCommandEvent;
12 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
13 use Symfony\Component\Console\Command\Command;
14 use Drupal\Console\Core\Utils\TranslatorManagerInterface;
15 use Drupal\Console\Core\Style\DrupalStyle;
16
17 /**
18  * Class ShowTipsListener
19  *
20  * @package Drupal\Console\Core\EventSubscriber
21  */
22 class ShowTipsListener implements EventSubscriberInterface
23 {
24     /**
25      * @var TranslatorManagerInterface
26      */
27     protected $translator;
28
29     /**
30      * ShowGenerateChainListener constructor.
31      *
32      * @param TranslatorManagerInterface $translator
33      */
34     public function __construct(
35         TranslatorManagerInterface $translator
36     ) {
37         $this->translator = $translator;
38     }
39
40     /**
41      * @param ConsoleCommandEvent $event
42      */
43     public function showTips(ConsoleCommandEvent $event)
44     {
45         /* @var Command $command */
46         $command = $event->getCommand();
47         $input = $command->getDefinition();
48         /* @var DrupalStyle $io */
49         $io = new DrupalStyle($event->getInput(), $event->getOutput());
50
51         $learning = $input->getOption('learning');
52
53         // pick randomly one of the tips (5 tips as maximum).
54         $tips = $this->getTip($command->getName());
55
56         if ($learning && $tips) {
57             $io->commentBlock($tips);
58         }
59     }
60
61     /**
62      * @param $commandName
63      * @return bool|string
64      */
65     private function getTip($commandName)
66     {
67         $get_tip = $this->translator
68             ->trans('commands.'.str_replace(':', '.', $commandName).'.tips.0.tip');
69         preg_match("/^commands./", $get_tip, $matches, null, 0);
70         if (!empty($matches)) {
71             return false;
72         }
73
74         $n = rand(0, 5);
75         $get_tip = $this->translator
76             ->trans('commands.'.str_replace(':', '.', $commandName).'.tips.' . $n . '.tip');
77         preg_match("/^commands./", $get_tip, $matches, null, 0);
78
79         if (empty($matches)) {
80             return $get_tip;
81         } else {
82             return $this->getTip($commandName);
83         }
84     }
85
86     /**
87      * @{@inheritdoc}
88      */
89     public static function getSubscribedEvents()
90     {
91         return [ConsoleEvents::COMMAND => 'showTips'];
92     }
93 }