FetchCommand::configure()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 9
nc 1
nop 0
crap 1
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\FetchErrorEvent;
13
use RunOpenCode\Bundle\ExchangeRate\Event\FetchEvents;
14
use RunOpenCode\Bundle\ExchangeRate\Event\FetchSuccessEvent;
15
use RunOpenCode\Bundle\ExchangeRate\Exception\InvalidArgumentException;
16
use RunOpenCode\Bundle\ExchangeRate\Exception\RuntimeException;
17
use RunOpenCode\ExchangeRate\Contract\ManagerInterface;
18
use RunOpenCode\ExchangeRate\Contract\RateInterface;
19
use RunOpenCode\ExchangeRate\Contract\SourceInterface;
20
use RunOpenCode\ExchangeRate\Contract\SourcesRegistryInterface;
21
use Symfony\Component\Console\Command\Command;
22
use Symfony\Component\Console\Input\InputInterface;
23
use Symfony\Component\Console\Input\InputOption;
24
use Symfony\Component\Console\Output\OutputInterface;
25
use Symfony\Component\Console\Style\SymfonyStyle;
26
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
27
28
/**
29
 * Class FetchCommand
30
 *
31
 * Fetch rates from sources.
32
 *
33
 * @package RunOpenCode\Bundle\ExchangeRate\Command
34
 */
35
class FetchCommand extends Command
36
{
37
    /**
38
     * @var EventDispatcherInterface
39
     */
40
    protected $eventDispatcher;
41
42
    /**
43
     * @var ManagerInterface
44
     */
45
    protected $manager;
46
47
    /**
48
     * @var SourcesRegistryInterface
49
     */
50
    protected $sourcesRegistry;
51
52
    /**
53
     * @var SymfonyStyle
54
     */
55
    protected $output;
56
57 9
    public function __construct(EventDispatcherInterface $eventDispatcher, ManagerInterface $manager, SourcesRegistryInterface $sourcesRegistry)
58
    {
59 9
        parent::__construct();
60 9
        $this->eventDispatcher = $eventDispatcher;
61 9
        $this->manager = $manager;
62 9
        $this->sourcesRegistry = $sourcesRegistry;
63 9
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 9
    protected function configure()
69
    {
70
        $this
71 9
            ->setName('runopencode:exchange-rate:fetch')
72 9
            ->setAliases([
73 9
                'roc:exchange-rate:fetch'
74
            ])
75 9
            ->setDescription('Fetch exchange rates from sources.')
76 9
            ->addOption('date', 'd', InputOption::VALUE_OPTIONAL, 'State on which date exchange rates should be fetched.')
77 9
            ->addOption('source', 'src', InputOption::VALUE_OPTIONAL, 'State which sources should be contacted only, separated with comma.')
78 9
            ->addOption('silent', null, InputOption::VALUE_OPTIONAL, 'In silent mode, rates are fetched, but no event will be fired.', false)
79
        ;
80 9
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85 9
    protected function execute(InputInterface $input, OutputInterface $output)
86
    {
87 9
        $this->output = new SymfonyStyle($input, $output);
88 9
        $date = (null !== $input->getOption('date')) ? $this->sanitizeDate($input->getOption('date')) : new \DateTime('now');
89 8
        $sources = $this->sanitizeSources($input->getOption('source'));
90 7
        $this->output->title(sprintf('Fetching rates for sources "%s" on "%s".', implode('", "', $sources), $date->format('Y-m-d')));
91
92 7
        $errors = [];
93 7
        $fetched = [];
94
95 7
        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...
96
97
            try {
98 7
                $rates = $this->manager->fetch($source, $date);
99
100 7
                if (0 === count($rates)) {
101 3
                    throw new RuntimeException(sprintf('No rate fetched from source "%s".', $source));
102
                }
103
104 6
                $rows = array_map(function(RateInterface $rate) {
105
                    return [
106 6
                        $rate->getCurrencyCode(),
107 6
                        $rate->getRateType(),
108 6
                        $rate->getValue(),
109
                    ];
110 6
                }, $rates);
111
112 6
                $this->output->section(sprintf('Fetched rates for source "%s":', $source));
113 6
                $this->output->table(['Currency code', 'Rate type', 'Value'], $rows);
114
115 6
                $fetched[$source] = $rates;
116
117 3
            } catch (\Exception $e) {
118 3
                $this->output->error(sprintf('Could not fetch rates from source "%s" (%s).', $source, $e->getMessage()));
119 7
                $errors[$source] = $e;
120
            }
121
        }
122
123 7
        if (!$input->getOption('silent')) {
124
125 6
            if (count($fetched) > 0) {
126 5
                $this->eventDispatcher->dispatch(FetchEvents::SUCCESS, new FetchSuccessEvent($fetched, $date));
127
            }
128
129 6
            if (count($errors) > 0) {
130 2
                $this->eventDispatcher->dispatch(FetchEvents::ERROR, new FetchErrorEvent($errors, $date));
131
            }
132
        }
133
134 7
        if ($errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
135 3
            $this->output->error('Could not fetch all rates.');
136 3
            return -1;
137
        }
138
139 4
        $this->output->success('Rates successfully fetched.');
140 4
        return 0;
141
    }
142
143
    /**
144
     * Sanitizes a date from console input.
145
     *
146
     * @param string|\DateTime $dateString A date
147
     *
148
     * @return \DateTime
149
     *
150
     * @throws InvalidArgumentException
151
     */
152 2
    protected function sanitizeDate($dateString)
153
    {
154
155 2
        $date = \DateTime::createFromFormat('Y-m-d', $dateString);
156
157 2
        if ($date instanceof \DateTime) {
158 1
            return $date;
159
        }
160
161
        try {
162 2
            $date = new \DateTime($dateString);
163 1
        } catch (\Exception $e) {
164
            // noop
165
        }
166
167
168 2
        if ($date instanceof \DateTime) {
169 1
            return $date;
170
        }
171
172 1
        throw new InvalidArgumentException(sprintf('Provided date "%s" is provided in unknown format. You should use "Y-m-d" instead.', $dateString));
173
    }
174
175
    /**
176
     * Clean sources from console input.
177
     *
178
     * @param mixed $sourcesString A sources.
179
     *
180
     * @return array|null
181
     *
182
     * @throws InvalidArgumentException
183
     */
184 8
    protected function sanitizeSources($sourcesString)
185
    {
186 8
        $sources = $sourcesString;
187
188 8
        if (is_string($sources)) {
189 6
            $sources = array_map('trim', explode(',', $sources));
190
        }
191
192 8
        if (null === $sources || (is_array($sources) && count($sources) === 0)) {
193
194 2
            return array_map(function(SourceInterface $source) {
195 2
                return $source->getName();
196 2
            }, $this->sourcesRegistry->all());
197
        }
198
199
        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...
200
            if (!$this->sourcesRegistry->has($source)) {
201
                throw new InvalidArgumentException(sprintf('Unknown source "%s" provided.', $source));
202
            }
203
        }
204
205
        return $sources;
206
    }
207
}
208