Completed
Branch master (58a10f)
by Timothy
02:24
created

RandomComplimentCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 14
rs 9.4285
cc 1
eloc 11
nc 1
nop 0
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
    protected function configure()
17
    {
18
        $this->setName('random:compliment')
19
            ->setDescription('Compliment user')
20
            ->addOption(
21
                'file',
22
                'f',
23
                InputOption::VALUE_OPTIONAL,
24
                'Source file',
25
                realpath(dirname(dirname(__DIR__)) . '/compliments.txt')
26
            )
27
            ->addOption('width', 'w', InputOption::VALUE_OPTIONAL, 'Console width', 80)
28
            ->addOption('delimiter', 'd', InputOption::VALUE_OPTIONAL, 'Console delimiter', '=');
29
    }
30
31
    /**
32
     * @param InputInterface $input
33
     * @param OutputInterface $output
34
     * @return int|null|void
35
     * @throws \InvalidArgumentException
36
     */
37
    protected function execute(InputInterface $input, OutputInterface $output)
38
    {
39
        $compliments = $this->getCompliments($input);
40
        $compliment = $compliments[array_rand($compliments)];
41
42
        $consoleWidth = $input->getOption('width');
43
        $boundaryDelimiter = $input->getOption('delimiter');
44
        $boundary = str_repeat($boundaryDelimiter, $consoleWidth);
45
        
46
        $output->writeln($boundary . PHP_EOL);
47
        $output->writeln(sprintf('By the way... %s', $compliment));
48
        $output->writeln($boundary);
49
    }
50
51
    /**
52
     * @param InputInterface $input
53
     * @return string[]
54
     * @throws \InvalidArgumentException
55
     */
56
    protected function getCompliments(InputInterface $input)
57
    {
58
        $file = $input->getOption('file');
59
60
        if (!is_file($file)) {
61
            throw new \InvalidArgumentException(sprintf('Path [%s] is not a file.', $file));
62
        }
63
64
        if (!is_readable($file)) {
65
            throw new \InvalidArgumentException(sprintf('File [%s] is not readable.', $file));
66
        }
67
68
        return file($file);
69
    }
70
}
71