InteractsWithAuthors::isAuthorsNodeEmpty()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 4.25

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 10
cc 4
nc 2
nop 1
crap 4.25
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpEpub\Traits;
6
7
use SimpleXMLElement;
8
9
trait InteractsWithAuthors
10
{
11
    private readonly SimpleXMLElement $opfXml;
12
    private readonly string $dcNamespace;
13
14
    /**
15
     * Gets the authors of the EPUB.
16
     *
17
     * @return array<int, string>
18
     */
19 9
    public function getAuthors(): array
20
    {
21 9
        $this->opfXml->registerXPathNamespace('dc', $this->dcNamespace);
22
23 9
        $creatorNodes = $this->opfXml->xpath('//dc:creator');
24
25 9
        if ($this->isAuthorsNodeEmpty($creatorNodes)) {
26
            return [];
27
        }
28
29 9
        $authors = [];
30 9
        foreach ($creatorNodes as $creatorNode) {
31 9
            $authors[] = (string) $creatorNode;
32
        }
33 9
        return $authors;
34
    }
35
36
    /**
37
     * Sets the authors of the EPUB.
38
     *
39
     * @param array<int, string> $authors
40
     */
41 1
    public function setAuthors(array $authors): void
42
    {
43 1
        $this->opfXml->registerXPathNamespace('dc', $this->dcNamespace);
44
45 1
        $creatorNodes = $this->opfXml->xpath('//dc:creator');
46
47 1
        if (! $this->isAuthorsNodeEmpty($creatorNodes)) {
48 1
            foreach ($creatorNodes as $key => $creatorNode) {
49 1
                unset($creatorNodes[$key][0]);
50
            }
51
        }
52
53 1
        foreach ($authors as $author) {
54 1
            $this->opfXml->metadata->addChild('creator', $author, $this->dcNamespace);
55
        }
56
    }
57
58
    /**
59
     * @param array<SimpleXMLElement>|false|null $creatorNodes
60
     *
61
     * @phpstan-assert-if-false array<SimpleXMLElement> $creatorNodes
62
     */
63 9
    private function isAuthorsNodeEmpty(mixed $creatorNodes): bool
64
    {
65 9
        if ($creatorNodes === false || $creatorNodes === null || $creatorNodes === []) {
66
            return true;
67
        }
68
69 9
        return false;
70
    }
71
}
72