Completed
Push — master ( 072588...3032d9 )
by Nikola
05:10
created

FetchCommand::execute()   C

Complexity

Conditions 8
Paths 76

Size

Total Lines 50
Code Lines 31

Duplication

Lines 6
Ratio 12 %

Code Coverage

Tests 20
CRAP Score 9.4924

Importance

Changes 0
Metric Value
dl 6
loc 50
ccs 20
cts 28
cp 0.7143
rs 6.3636
c 0
b 0
f 0
cc 8
eloc 31
nc 76
nop 2
crap 9.4924
1
<?php
2
/*
3
 * This file is part of the Exchange Rate Bundle, an RunOpenCode project.
4
 *
5
 * (c) 2017 RunOpenCode
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace RunOpenCode\Bundle\ExchangeRate\Command;
11
12
use RunOpenCode\Bundle\ExchangeRate\Event\FetchEvents;
13
use RunOpenCode\Bundle\ExchangeRate\Exception\InvalidArgumentException;
14
use RunOpenCode\Bundle\ExchangeRate\Exception\RuntimeException;
15
use RunOpenCode\ExchangeRate\Contract\ManagerInterface;
16
use RunOpenCode\ExchangeRate\Contract\RateInterface;
17
use RunOpenCode\ExchangeRate\Contract\SourceInterface;
18
use RunOpenCode\ExchangeRate\Contract\SourcesRegistryInterface;
19
use Symfony\Component\Console\Command\Command;
20
use Symfony\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Input\InputOption;
22
use Symfony\Component\Console\Output\OutputInterface;
23
use Symfony\Component\Console\Style\SymfonyStyle;
24
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
25
use Symfony\Component\EventDispatcher\GenericEvent;
26
27
/**
28
 * Class FetchCommand
29
 *
30
 * Fetch rates from sources.
31
 *
32
 * @package RunOpenCode\Bundle\ExchangeRate\Command
33
 */
34
class FetchCommand extends Command
35
{
36
    /**
37
     * @var EventDispatcherInterface
38
     */
39
    protected $eventDispatcher;
40
41
    /**
42
     * @var ManagerInterface
43
     */
44
    protected $manager;
45
46
    /**
47
     * @var SourcesRegistryInterface
48
     */
49
    protected $sourcesRegistry;
50
51
    /**
52
     * @var SymfonyStyle
53
     */
54
    protected $output;
55
56 6
    public function __construct(EventDispatcherInterface $eventDispatcher, ManagerInterface $manager, SourcesRegistryInterface $sourcesRegistry)
57
    {
58 6
        parent::__construct();
59 6
        $this->eventDispatcher = $eventDispatcher;
60 6
        $this->manager = $manager;
61 6
        $this->sourcesRegistry = $sourcesRegistry;
62 6
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 6
    protected function configure()
68
    {
69
        $this
70 6
            ->setName('runopencode:exchange-rate:fetch')
71 6
            ->setAliases([
72
                'roc:exchange-rate:fetch'
73 6
            ])
74 6
            ->setDescription('Fetch exchange rates from sources.')
75 6
            ->addOption('date', 'd', InputOption::VALUE_OPTIONAL, 'State on which date exchange rates should be fetched.')
76 6
            ->addOption('source', 'src', InputOption::VALUE_OPTIONAL, 'State which sources should be contacted only, separated with comma.')
77 6
            ->addOption('silent', null, InputOption::VALUE_OPTIONAL, 'In silent mode, rates are fetched, but no event will be fired.', false)
78
        ;
79 6
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84 6
    protected function execute(InputInterface $input, OutputInterface $output)
85
    {
86 6
        $this->output = new SymfonyStyle($input, $output);
87 6
        $date = (null !== $input->getOption('date')) ? $this->sanitizeDate($input->getOption('date')) : new \DateTime('now');
88 5
        $sources = $this->sanitizeSources($input->getOption('source'));
89 4
        $this->output->title(sprintf('Fetching rates for sources "%s" on "%s".', implode('", "', $sources), $date->format('Y-m-d')));
90
91 4
        $errors = false;
92
93 4
        foreach ($sources as $source) {
0 ignored issues
show
Bug introduced by
The expression $sources of type array|object|integer|double|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
94
95
            try {
96 4
                $rates = $this->manager->fetch($source, $date);
97
98 4
                if (0 === count($rates)) {
99
                    throw new RuntimeException(sprintf('No rate fetched from source "%s".', $source));
100
                }
101
102
                $rows = array_map(function(RateInterface $rate) {
103
                    return [
104 4
                        $rate->getCurrencyCode(),
105 4
                        $rate->getRateType(),
106 4
                        $rate->getValue(),
107
                    ];
108 4
                }, $rates);
109
110 4
                $this->output->section(sprintf('Fetched rates for source "%s":', $source));
111 4
                $this->output->table(['Currency code', 'Rate type', 'Value'], $rows);
112
113 4 View Code Duplication
                if (!$input->getOption('silent')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
114 4
                    $this->eventDispatcher->dispatch(FetchEvents::SUCCESS, new GenericEvent($sources, ['rates' => $rates]));
115
                }
116
            } catch (\Exception $e) {
117
                $this->output->error(sprintf('Could not fetch rates from source "%s" (%s).', $source, $e->getMessage()));
118
                $errors = true;
119
120 View Code Duplication
                if (!$input->getOption('silent')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
121
                    $this->eventDispatcher->dispatch(FetchEvents::ERROR, new GenericEvent($sources, ['exception' => $e]));
122
                }
123
            }
124
        }
125
126 4
        if ($errors) {
127
            $this->output->error('Could not fetch all rates.');
128
            return -1;
129
        }
130
131 4
        $this->output->success('Rates successfully fetched.');
132 4
        return 0;
133
    }
134
135
    /**
136
     * Sanitizes a date from console input.
137
     *
138
     * @param string|\DateTime $dateString A date
139
     *
140
     * @return \DateTime
141
     *
142
     * @throws InvalidArgumentException
143
     */
144 2
    protected function sanitizeDate($dateString)
145
    {
146
147 2
        $date = \DateTime::createFromFormat('Y-m-d', $dateString);
148
149 2
        if ($date instanceof \DateTime) {
150 1
            return $date;
151
        }
152
153
        try {
154 2
            $date = new \DateTime($dateString);
155 1
        } catch (\Exception $e) {
156
            // noop
157
        }
158
159
160 2
        if ($date instanceof \DateTime) {
161 1
            return $date;
162
        }
163
164 1
        throw new InvalidArgumentException(sprintf('Provided date "%s" is provided in unknown format. You should use "Y-m-d" instead.', $dateString));
165
    }
166
167
    /**
168
     * Clean sources from console input.
169
     *
170
     * @param mixed $sourcesString A sources.
171
     *
172
     * @return array|null
173
     *
174
     * @throws InvalidArgumentException
175
     */
176 5
    protected function sanitizeSources($sourcesString)
177
    {
178 5
        $sources = $sourcesString;
179
180 5
        if (is_string($sources)) {
181 3
            $sources = array_map('trim', explode(',', $sources));
182
        }
183
184 5
        if (null === $sources || (is_array($sources) && count($sources) === 0)) {
185
186 2
            return array_map(function(SourceInterface $source) {
187 2
                return $source->getName();
188 2
            }, $this->sourcesRegistry->all());
189
        }
190
191 3
        foreach ($sources as $source) {
0 ignored issues
show
Bug introduced by
The expression $sources of type object|integer|double|boolean|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
192 3
            if (!$this->sourcesRegistry->has($source)) {
193 1
                throw new InvalidArgumentException(sprintf('Unknown source "%s" provided.', $source));
194
            }
195
        }
196
197 2
        return $sources;
198
    }
199
}
200