ReadTrait::readItem()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 5
c 2
b 1
f 0
dl 0
loc 12
rs 10
cc 3
nc 3
nop 4
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
use Generator;
20
use InvalidArgumentException;
21
22
/**
23
 * Trait for reading files.
24
 */
25
trait ReadTrait
26
{
27
    use InstanceConfigTrait;
28
    use FileTrait;
29
    use CsvTrait;
30
    use XmlTrait;
31
32
    /**
33
     * Read a CSV or XML file.
34
     *
35
     * @param string $sourceType Source type: 'csv' or 'xml'
36
     * @param string $path Path to file
37
     * @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.
38
     * @param string $element Element name for XML files
39
     * @return \Generator<array<array-key, string>>
40
     */
41
    protected function readItem(
42
        string $sourceType,
43
        string $path,
44
        bool $assoc = true,
45
        string $element = 'post',
46
    ): Generator {
47
        if (!in_array($sourceType, ['csv', 'xml'])) {
48
            throw new InvalidArgumentException(sprintf('Invalid source type "%s"', $sourceType));
49
        }
50
        $method = 'read' . ucfirst($sourceType);
51
        $params = $sourceType === 'csv' ? [$path, $assoc] : [$path, $element];
52
        yield from $this->$method(...$params);
53
    }
54
}
55