Passed
Pull Request — master (#1013)
by lee
07:38
created

DataLoad::process()   B

Complexity

Conditions 9
Paths 13

Size

Total Lines 69
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 47
CRAP Score 9.0721

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 52
c 1
b 0
f 0
nc 13
nop 0
dl 0
loc 69
ccs 47
cts 52
cp 0.9038
crap 9.0721
rs 7.4917

How to fix   Long Method   

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
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil\Step;
12
13
use Cecil\Util;
14
use Symfony\Component\Finder\Finder;
15
use Symfony\Component\Serializer\Encoder\CsvEncoder;
16
use Symfony\Component\Serializer\Encoder\JsonEncoder;
17
use Symfony\Component\Serializer\Encoder\XmlEncoder;
18
use Symfony\Component\Serializer\Encoder\YamlEncoder;
19
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
20
use Symfony\Component\Serializer\Serializer;
21
22
/**
23
 * Loads data files.
24
 */
25
class DataLoad extends AbstractStep
26
{
27
    /**
28
     * {@inheritdoc}
29
     */
30 1
    public function getName(): string
31
    {
32 1
        return 'Loading data';
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 1
    public function init($options)
39
    {
40
        /** @var \Cecil\Builder $builder */
41
        /** @var \Cecil\Config $config */
42 1
        if (is_dir($this->builder->getConfig()->getDataPath()) && $this->config->get('data.load')) {
43 1
            $this->canProcess = true;
44
        }
45 1
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 1
    public function process()
51
    {
52 1
        $files = Finder::create()
53 1
            ->files()
54 1
            ->in($this->builder->getConfig()->getDataPath())
55 1
            ->name('/\.('.implode('|', (array) $this->builder->getConfig()->get('data.ext')).')$/')
56 1
            ->sortByName(true);
57 1
        $max = count($files);
58
59 1
        if ($max <= 0) {
60
            $message = 'No files';
61
            $this->builder->getLogger()->info($message);
62
63
            return;
64
        }
65
66 1
        $serializerYaml = new Serializer([new ObjectNormalizer()], [new YamlEncoder()]);
67 1
        $serializerJson = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
68 1
        $serializerCsv = new Serializer([new ObjectNormalizer()], [new CsvEncoder()]);
69 1
        $serializerXml = new Serializer([new ObjectNormalizer()], [new XmlEncoder()]);
70 1
        $count = 0;
71
72
        /** @var \Symfony\Component\Finder\SplFileInfo $file */
73 1
        foreach ($files as $file) {
74 1
            $count++;
75 1
            set_error_handler(
76
                function ($severity, $message, $file, $line) {
77
                    throw new \ErrorException($message, 0, $severity, $file, $line, null);
78 1
                }
79
            );
80 1
            $data = $file->getContents();
81 1
            restore_error_handler();
82
83 1
            switch ($file->getExtension()) {
84 1
                case 'yml':
85 1
                case 'yaml':
86 1
                    $dataArray = $serializerYaml->decode($data, 'yaml');
87 1
                    break;
88 1
                case 'json':
89 1
                    $dataArray = $serializerJson->decode($data, 'json');
90 1
                    break;
91 1
                case 'csv':
92 1
                    $dataArray = $serializerCsv->decode($data, 'csv');
93 1
                    break;
94 1
                case 'xml':
95 1
                    $dataArray = $serializerXml->decode($data, 'xml');
96 1
                    break;
97
                default:
98
                    return;
99
            }
100
101 1
            $basename = $file->getBasename('.'.$file->getExtension());
102 1
            $subpath = \Cecil\Util::getFS()->makePathRelative(
103 1
                $file->getPath(),
104 1
                $this->builder->getConfig()->getDataPath()
105
            );
106 1
            $subpath = trim($subpath, './');
107 1
            $array = [];
108 1
            $path = !empty($subpath) ? Util::joinFile($subpath, $basename) : $basename;
109 1
            $this->pathToArray($array, $path, $dataArray);
110
111 1
            $dataArray = array_merge_recursive(
112 1
                $this->builder->getData(),
113 1
                $array
114
            );
115 1
            $this->builder->setData($dataArray);
116
117 1
            $message = sprintf('%s.%s', Util::joinFile($path), $file->getExtension());
118 1
            $this->builder->getLogger()->info($message, ['progress' => [$count, $count]]);
119
        }
120 1
    }
121
122
    /**
123
     * Converts a path to an array.
124
     *
125
     * @param array  $arr       Target array
126
     * @param string $path      Source path
127
     * @param array  $value     Source values
128
     * @param string $separator Separator (ie: /)
129
     */
130 1
    private function pathToArray(array &$arr, string $path, array $value, string $separator = DIRECTORY_SEPARATOR): void
131
    {
132 1
        $keys = explode($separator, $path);
133
134 1
        foreach ($keys as $key) {
135 1
            $arr = &$arr[$key];
136
        }
137
138 1
        $arr = $value;
139 1
    }
140
}
141