Passed
Pull Request — master (#1955)
by Arnaud
09:06 queued 03:50
created

Load::process()   B

Complexity

Conditions 10
Paths 23

Size

Total Lines 75
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 54
CRAP Score 10.1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 56
c 1
b 0
f 0
nc 23
nop 0
dl 0
loc 75
ccs 54
cts 60
cp 0.9
crap 10.1
rs 7.0933

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Step\Data;
15
16
use Cecil\Collection\Page\PrefixSuffix;
17
use Cecil\Step\AbstractStep;
18
use Cecil\Util;
19
use Symfony\Component\Finder\Finder;
20
use Symfony\Component\Serializer\Encoder\CsvEncoder;
21
use Symfony\Component\Serializer\Encoder\JsonEncoder;
22
use Symfony\Component\Serializer\Encoder\XmlEncoder;
23
use Symfony\Component\Serializer\Encoder\YamlEncoder;
24
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
25
use Symfony\Component\Serializer\Serializer;
26
27
/**
28
 * Loads data files.
29
 */
30
class Load extends AbstractStep
31
{
32
    /**
33
     * {@inheritdoc}
34
     */
35 1
    public function getName(): string
36
    {
37 1
        return 'Loading data';
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 1
    public function init(array $options): void
44
    {
45 1
        if (is_dir($this->config->getDataPath()) && (bool) $this->config->get('data.load')) {
46 1
            $this->canProcess = true;
47
        }
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53 1
    public function process(): void
54
    {
55 1
        $files = Finder::create()
56 1
            ->files()
57 1
            ->in($this->config->getDataPath())
58 1
            ->name('/\.(' . implode('|', (array) $this->config->get('data.ext')) . ')$/')
59 1
            ->sortByName(true);
60 1
        $total = \count($files);
61
62 1
        if ($total < 1) {
63
            $message = 'No files';
64
            $this->builder->getLogger()->info($message);
65
66
            return;
67
        }
68
69 1
        $serializerYaml = new Serializer([new ObjectNormalizer()], [new YamlEncoder()]);
70 1
        $serializerJson = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
71 1
        $serializerCsv = new Serializer([new ObjectNormalizer()], [new CsvEncoder()]);
72 1
        $serializerXml = new Serializer([new ObjectNormalizer()], [new XmlEncoder()]);
73 1
        $count = 0;
74
75
        /** @var \Symfony\Component\Finder\SplFileInfo $file */
76 1
        foreach ($files as $file) {
77 1
            $count++;
78 1
            set_error_handler(
79 1
                function ($severity, $message, $file, $line) {
80
                    throw new \ErrorException($message, 0, $severity, $file, $line, null);
81 1
                }
82 1
            );
83 1
            $data = $file->getContents();
84 1
            restore_error_handler();
85
86 1
            switch ($file->getExtension()) {
87 1
                case 'yml':
88 1
                case 'yaml':
89 1
                    $dataAsArray = $serializerYaml->decode($data, 'yaml');
90 1
                    break;
91 1
                case 'json':
92 1
                    $dataAsArray = $serializerJson->decode($data, 'json');
93 1
                    break;
94 1
                case 'csv':
95 1
                    $dataAsArray = $serializerCsv->decode($data, 'csv');
96 1
                    break;
97 1
                case 'xml':
98 1
                    $dataAsArray = $serializerXml->decode($data, 'xml');
99 1
                    break;
100
                default:
101
                    return;
102
            }
103
104 1
            $lang = $this->config->getLanguageDefault();
105 1
            if (PrefixSuffix::hasSuffix($file->getBasename('.' . $file->getExtension()))) {
106
                $lang = PrefixSuffix::getSuffix($file->getBasename('.' . $file->getExtension()));
107
            }
108 1
            $basename = $file->getBasename('.' . $file->getExtension());
109 1
            $subpath = \Cecil\Util\File::getFS()->makePathRelative(
110 1
                $file->getPath(),
111 1
                $this->config->getDataPath()
112 1
            );
113 1
            $subpath = trim($subpath, './');
114 1
            $array = [];
115 1
            $path = !empty($subpath) ? Util::joinFile($subpath, $basename) : $basename;
116 1
            $localizedPath = Util::joinFile($lang, PrefixSuffix::sub($path));
0 ignored issues
show
Bug introduced by
It seems like $lang can also be of type null; however, parameter $path of Cecil\Util::joinFile() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

116
            $localizedPath = Util::joinFile(/** @scrutinizer ignore-type */ $lang, PrefixSuffix::sub($path));
Loading history...
117 1
            $this->pathToArray($array, $localizedPath, $dataAsArray);
118
119 1
            $dataAsArray = array_merge_recursive(
120 1
                $this->builder->getData(),
121 1
                $array
122 1
            );
123 1
            $this->builder->setData($dataAsArray);
124
125 1
            $message = sprintf('File "%s.%s" loaded', Util::joinFile($path), $file->getExtension());
126
            //$message = sprintf('File "%s" loaded', $file->getBasename());
127 1
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
128
        }
129
    }
130
131
    /**
132
     * Puts a path/value couple into an array.
133
     *
134
     * @param array  $arr       Target array
135
     * @param string $path      Source path
136
     * @param array  $value     Source values
137
     * @param string $separator Path separator (ie: '/')
138
     */
139 1
    private function pathToArray(array &$arr, string $path, array $value, string $separator = DIRECTORY_SEPARATOR): void
140
    {
141 1
        $keys = explode($separator, $path);
142 1
        foreach ($keys as $key) {
143 1
            $arr = &$arr[$key];
144
        }
145 1
        $arr = $value;
146
    }
147
}
148