Passed
Push — nested-sections-2025 ( e7a7c2...4fb8cc )
by Arnaud
05:03
created

Load::process()   C

Complexity

Conditions 12
Paths 26

Size

Total Lines 79
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 54
CRAP Score 12.144

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 57
c 1
b 0
f 0
nc 26
nop 0
dl 0
loc 79
ccs 54
cts 60
cp 0.9
crap 12.144
rs 6.5115

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
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
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
 * Load step class.
29
 *
30
 * This class is responsible for loading data files from a specified directory,
31
 * decoding their contents based on the file extension, and merging the data
32
 * into the builder's data collection. It supports various file formats such as
33
 * YAML, JSON, CSV, and XML. The loaded data is organized into a nested array
34
 * structure based on the file paths and language suffixes.
35
 */
36
class Load extends AbstractStep
37
{
38
    /**
39
     * {@inheritdoc}
40
     */
41 1
    public function getName(): string
42
    {
43 1
        return 'Loading data';
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49 1
    public function init(array $options): void
50
    {
51 1
        if (is_dir($this->config->getDataPath()) && $this->config->isEnabled('data.load')) {
52 1
            $this->canProcess = true;
53
        }
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 1
    public function process(): void
60
    {
61 1
        $files = Finder::create()
62 1
            ->files()
63 1
            ->in($this->config->getDataPath())
64 1
            ->name('/\.(' . implode('|', (array) $this->config->get('data.ext')) . ')$/')
65 1
            ->sortByName(true);
66 1
67
        if ($this->config->hasTheme()) {
68 1
            $themes = $this->config->getTheme();
69
            foreach ($themes ?? [] as $theme) {
70
                if (Util\File::getFS()->exists($this->config->getThemeDirPath($theme, 'data'))) {
71
                    $files->in($this->config->getThemeDirPath($theme, 'data'));
72
                }
73
            }
74
        }
75 1
76 1
        $total = \count($files);
77 1
78 1
        if ($total < 1) {
79 1
            $message = 'No files';
80
            $this->builder->getLogger()->info($message);
81
82 1
            return;
83 1
        }
84 1
85 1
        $serializerYaml = new Serializer([new ObjectNormalizer()], [new YamlEncoder()]);
86
        $serializerJson = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
87 1
        $serializerCsv = new Serializer([new ObjectNormalizer()], [new CsvEncoder()]);
88 1
        $serializerXml = new Serializer([new ObjectNormalizer()], [new XmlEncoder()]);
89 1
        $count = 0;
90 1
91
        /** @var \Symfony\Component\Finder\SplFileInfo $file */
92 1
        foreach ($files as $file) {
93 1
            $count++;
94 1
            set_error_handler(
95 1
                function ($severity, $message, $file, $line) {
96 1
                    throw new \ErrorException($message, 0, $severity, $file, $line, null);
97 1
                }
98 1
            );
99 1
            $data = $file->getContents();
100 1
            restore_error_handler();
101 1
102 1
            switch ($file->getExtension()) {
103 1
                case 'yml':
104 1
                case 'yaml':
105 1
                    $dataAsArray = $serializerYaml->decode($data, 'yaml');
106
                    break;
107
                case 'json':
108
                    $dataAsArray = $serializerJson->decode($data, 'json');
109
                    break;
110 1
                case 'csv':
111 1
                    $dataAsArray = $serializerCsv->decode($data, 'csv');
112
                    break;
113
                case 'xml':
114 1
                    $dataAsArray = $serializerXml->decode($data, 'xml');
115 1
                    break;
116 1
                default:
117 1
                    return;
118 1
            }
119 1
120 1
            $lang = $this->config->getLanguageDefault();
121 1
            if (PrefixSuffix::hasSuffix($file->getFilenameWithoutExtension())) {
122 1
                $lang = PrefixSuffix::getSuffix($file->getFilenameWithoutExtension());
123 1
            }
124
            $array = [];
125 1
            $path = Util::joinFile((string) pathinfo($file->getRelativePathname(), \PATHINFO_DIRNAME), (string) pathinfo($file->getRelativePathname(), \PATHINFO_FILENAME));
126 1
            $path = trim($path, './');
127 1
            $localizedPath = Util::joinFile((string) $lang, PrefixSuffix::sub($path));
128 1
            $this->pathToArray($array, $localizedPath, $dataAsArray);
129 1
130
            $dataAsArray = array_merge_recursive(
131 1
                $this->builder->getData(),
132 1
                $array
133
            );
134
            $this->builder->setData($dataAsArray);
135
136
            $message = \sprintf('File "%s" loaded', $file->getRelativePathname());
137
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
138
        }
139
    }
140
141
    /**
142
     * Puts a path/value couple into an array.
143
     *
144 1
     * @param array  $arr       Target array
145
     * @param string $path      Source path
146 1
     * @param array  $value     Source values
147 1
     * @param string $separator Path separator (ie: '/')
148 1
     */
149
    private function pathToArray(array &$arr, string $path, array $value, string $separator = DIRECTORY_SEPARATOR): void
150 1
    {
151
        $keys = explode($separator, $path);
152
        foreach ($keys as $key) {
153
            $arr = &$arr[$key];
154
        }
155
        $arr = $value;
156
    }
157
}
158