ReadTrait   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 10
c 1
b 0
f 0
dl 0
loc 24
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A readItem() 0 8 3
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * BEdita, API-first content management framework
6
 * Copyright 2024 Atlas Srl, Chialab Srl
7
 *
8
 * This file is part of BEdita: you can redistribute it and/or modify
9
 * it under the terms of the GNU Lesser General Public License as published
10
 * by the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
14
 */
15
16
namespace BEdita\ImportTools\Utility;
17
18
use Cake\Core\InstanceConfigTrait;
19
20
/**
21
 * Trait for reading files.
22
 */
23
trait ReadTrait
24
{
25
    use InstanceConfigTrait;
26
    use FileTrait;
27
    use CsvTrait;
28
    use XmlTrait;
29
30
    /**
31
     * Read a CSV or XML file.
32
     *
33
     * @param string $sourceType Source type: 'csv' or 'xml'
34
     * @param string $path Path to file
35
     * @param bool $assoc If `true` uses first CSV row as column names, thus yielding associative arrays. Otherwise, all rows are yielded and columns are indexed by their positions.
36
     * @param string $element Element name for XML files
37
     * @return \Generator<array<array-key, string>>
38
     */
39
    protected function readItem(string $sourceType, string $path, bool $assoc = true, string $element = 'post'): \Generator
40
    {
41
        if (!in_array($sourceType, ['csv', 'xml'])) {
42
            throw new \InvalidArgumentException(sprintf('Invalid source type "%s"', $sourceType));
43
        }
44
        $method = 'read' . ucfirst($sourceType);
45
        $params = $sourceType === 'csv' ? [$path, $assoc] : [$path, $element];
46
        yield from $this->$method(...$params);
47
    }
48
}
49