Completed
Push — master ( 3032d9...a042d0 )
by Nikola
03:41
created

FetchCommand   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 166
Duplicated Lines 3.61 %

Coupling/Cohesion

Components 2
Dependencies 11

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 21
lcom 2
cbo 11
dl 6
loc 166
ccs 64
cts 64
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A configure() 0 13 1
B sanitizeDate() 0 22 4
C sanitizeSources() 0 23 7
C execute() 6 50 8

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 9
    public function __construct(EventDispatcherInterface $eventDispatcher, ManagerInterface $manager, SourcesRegistryInterface $sourcesRegistry)
57
    {
58 9
        parent::__construct();
59 9
        $this->eventDispatcher = $eventDispatcher;
60 9
        $this->manager = $manager;
61 9
        $this->sourcesRegistry = $sourcesRegistry;
62 9
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 9
    protected function configure()
68
    {
69
        $this
70 9
            ->setName('runopencode:exchange-rate:fetch')
71 9
            ->setAliases([
72
                'roc:exchange-rate:fetch'
73 9
            ])
74 9
            ->setDescription('Fetch exchange rates from sources.')
75 9
            ->addOption('date', 'd', InputOption::VALUE_OPTIONAL, 'State on which date exchange rates should be fetched.')
76 9
            ->addOption('source', 'src', InputOption::VALUE_OPTIONAL, 'State which sources should be contacted only, separated with comma.')
77 9
            ->addOption('silent', null, InputOption::VALUE_OPTIONAL, 'In silent mode, rates are fetched, but no event will be fired.', false)
78
        ;
79 9
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84 9
    protected function execute(InputInterface $input, OutputInterface $output)
85
    {
86 9
        $this->output = new SymfonyStyle($input, $output);
87 9
        $date = (null !== $input->getOption('date')) ? $this->sanitizeDate($input->getOption('date')) : new \DateTime('now');
88 8
        $sources = $this->sanitizeSources($input->getOption('source'));
89 7
        $this->output->title(sprintf('Fetching rates for sources "%s" on "%s".', implode('", "', $sources), $date->format('Y-m-d')));
90
91 7
        $errors = false;
92
93 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...
94
95
            try {
96 7
                $rates = $this->manager->fetch($source, $date);
97
98 7
                if (0 === count($rates)) {
99 3
                    throw new RuntimeException(sprintf('No rate fetched from source "%s".', $source));
100
                }
101
102
                $rows = array_map(function(RateInterface $rate) {
103
                    return [
104 6
                        $rate->getCurrencyCode(),
105 6
                        $rate->getRateType(),
106 6
                        $rate->getValue(),
107
                    ];
108 6
                }, $rates);
109
110 6
                $this->output->section(sprintf('Fetched rates for source "%s":', $source));
111 6
                $this->output->table(['Currency code', 'Rate type', 'Value'], $rows);
112
113 6 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 5
                    $this->eventDispatcher->dispatch(FetchEvents::SUCCESS, new GenericEvent($source, ['rates' => $rates]));
115
                }
116 3
            } catch (\Exception $e) {
117 3
                $this->output->error(sprintf('Could not fetch rates from source "%s" (%s).', $source, $e->getMessage()));
118 3
                $errors = true;
119
120 3 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 2
                    $this->eventDispatcher->dispatch(FetchEvents::ERROR, new GenericEvent($source, ['exception' => $e]));
122
                }
123
            }
124
        }
125
126 7
        if ($errors) {
127 3
            $this->output->error('Could not fetch all rates.');
128 3
            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 8
    protected function sanitizeSources($sourcesString)
177
    {
178 8
        $sources = $sourcesString;
179
180 8
        if (is_string($sources)) {
181 6
            $sources = array_map('trim', explode(',', $sources));
182
        }
183
184 8
        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 6
        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 6
            if (!$this->sourcesRegistry->has($source)) {
193 1
                throw new InvalidArgumentException(sprintf('Unknown source "%s" provided.', $source));
194
            }
195
        }
196
197 5
        return $sources;
198
    }
199
}
200