1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Abacaphiliac\Compliments; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Console\Command\Command; |
6
|
|
|
use Symfony\Component\Console\Input\InputInterface; |
7
|
|
|
use Symfony\Component\Console\Input\InputOption; |
8
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
9
|
|
|
|
10
|
|
|
class RandomComplimentCommand extends Command |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @throws \InvalidArgumentException |
14
|
|
|
* @throws \Symfony\Component\Console\Exception\InvalidArgumentException |
15
|
|
|
*/ |
16
|
5 |
|
protected function configure() |
17
|
|
|
{ |
18
|
5 |
|
$this->setName('random:compliment') |
19
|
5 |
|
->setDescription('Compliment user') |
20
|
5 |
|
->addOption( |
21
|
5 |
|
'file', |
22
|
5 |
|
'f', |
23
|
5 |
|
InputOption::VALUE_OPTIONAL, |
24
|
5 |
|
'Source file', |
25
|
5 |
|
realpath(dirname(dirname(__DIR__)) . '/compliments.txt') |
26
|
5 |
|
) |
27
|
5 |
|
->addOption('width', 'w', InputOption::VALUE_OPTIONAL, 'Console width', 80) |
28
|
5 |
|
->addOption('delimiter', 'd', InputOption::VALUE_OPTIONAL, 'Console delimiter', '='); |
29
|
5 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param InputInterface $input |
33
|
|
|
* @param OutputInterface $output |
34
|
|
|
* @return int|null|void |
35
|
|
|
* @throws \InvalidArgumentException |
36
|
|
|
*/ |
37
|
3 |
|
protected function execute(InputInterface $input, OutputInterface $output) |
38
|
|
|
{ |
39
|
3 |
|
$compliments = $this->getCompliments($input); |
40
|
1 |
|
$compliment = $compliments[array_rand($compliments)]; |
41
|
|
|
|
42
|
1 |
|
$consoleWidth = $input->getOption('width'); |
43
|
1 |
|
$boundaryDelimiter = $input->getOption('delimiter'); |
44
|
1 |
|
$boundary = str_repeat($boundaryDelimiter, $consoleWidth); |
45
|
|
|
|
46
|
1 |
|
$output->writeln($boundary . PHP_EOL); |
47
|
1 |
|
$output->writeln(sprintf('By the way... %s', $compliment)); |
48
|
1 |
|
$output->writeln($boundary); |
49
|
1 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param InputInterface $input |
53
|
|
|
* @return string[] |
54
|
|
|
* @throws \InvalidArgumentException |
55
|
|
|
*/ |
56
|
3 |
|
protected function getCompliments(InputInterface $input) |
57
|
|
|
{ |
58
|
3 |
|
$file = $input->getOption('file'); |
59
|
|
|
|
60
|
3 |
|
if (!is_file($file)) { |
61
|
1 |
|
throw new \InvalidArgumentException(sprintf('Path [%s] is not a file.', $file)); |
62
|
|
|
} |
63
|
|
|
|
64
|
2 |
|
if (!is_readable($file)) { |
65
|
1 |
|
throw new \InvalidArgumentException(sprintf('File [%s] is not readable.', $file)); |
66
|
|
|
} |
67
|
|
|
|
68
|
1 |
|
return file($file); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|