1 | <?php |
||
29 | final class BroadcastCommand extends AbstractCommand |
||
30 | { |
||
31 | use ArgumentDataTrait; |
||
32 | |||
33 | protected static $defaultName = 'centrifugo:broadcast'; |
||
34 | |||
35 | private CentrifugoChecker $centrifugoChecker; |
||
|
|||
36 | |||
37 | /** @var string[] */ |
||
38 | private array $channels; |
||
39 | |||
40 | /** |
||
41 | * @param CentrifugoInterface $centrifugo |
||
42 | * @param CentrifugoChecker $centrifugoChecker |
||
43 | */ |
||
44 | public function __construct(CentrifugoInterface $centrifugo, CentrifugoChecker $centrifugoChecker) |
||
45 | { |
||
46 | $this->centrifugoChecker = $centrifugoChecker; |
||
47 | |||
48 | parent::__construct($centrifugo); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * {@inheritdoc} |
||
53 | */ |
||
54 | protected function configure(): void |
||
55 | { |
||
56 | $this |
||
57 | ->setDescription('Publish same data into many channels') |
||
58 | ->setDefinition( |
||
59 | new InputDefinition([ |
||
60 | new InputArgument('data', InputArgument::REQUIRED, 'Data in JSON format'), |
||
61 | new InputArgument('channels', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'Channel names'), |
||
62 | ]) |
||
63 | ) |
||
64 | ->setHelp( |
||
65 | <<<'HELP' |
||
66 | The <info>%command.name%</info> command allows to publish same data into many channels: |
||
67 | |||
68 | <info>%command.full_name%</info> <comment>'{"foo":"bar"}'</comment> </comment>channelAbc</comment> </comment>channelDef</comment> |
||
69 | |||
70 | Read more at https://centrifugal.github.io/centrifugo/server/http_api/#broadcast |
||
71 | HELP |
||
72 | ) |
||
73 | ; |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * {@inheritdoc} |
||
78 | */ |
||
79 | protected function initialize(InputInterface $input, OutputInterface $output): void |
||
80 | { |
||
81 | parent::initialize($input, $output); |
||
82 | |||
83 | $this->initializeDataArgument($input); |
||
84 | |||
85 | try { |
||
86 | $channels = (array) $input->getArgument('channels'); |
||
87 | foreach ($channels as $channel) { |
||
88 | $this->centrifugoChecker->assertValidChannelName($channel); |
||
89 | } |
||
90 | $this->channels = $channels; |
||
91 | } catch (\Throwable $e) { |
||
92 | throw new InvalidArgumentException($e->getMessage()); |
||
93 | } |
||
94 | } |
||
95 | |||
96 | /** |
||
97 | * {@inheritdoc} |
||
98 | */ |
||
99 | protected function execute(InputInterface $input, OutputInterface $output): int |
||
100 | { |
||
101 | $io = new SymfonyStyle($input, $output); |
||
102 | |||
103 | try { |
||
104 | $this->centrifugo->broadcast($this->data, $this->channels); |
||
105 | $io->success('DONE'); |
||
106 | } catch (\Throwable $e) { |
||
107 | $io->error($e->getMessage()); |
||
108 | |||
109 | return $e->getCode(); |
||
110 | } |
||
111 | |||
112 | return 0; |
||
113 | } |
||
114 | } |
||
115 |