Passed
Push — master ( 79b269...cf2aaf )
by Sebastian
02:59
created

Xml::parseLogOutput()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 21
ccs 15
cts 15
cp 1
rs 9.7998
cc 3
nc 3
nop 1
crap 3
1
<?php
2
/**
3
 * This file is part of SebastianFeldmann/Git.
4
 *
5
 * (c) Sebastian Feldmann <[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
namespace SebastianFeldmann\Git\Command\Log\Commits;
11
12
use SebastianFeldmann\Git\Log\Commit;
13
14
/**
15
 * Class Xml
16
 *
17
 * @package SebastianFeldmann\Git
18
 * @author  Sebastian Feldmann <[email protected]>
19
 * @link    https://github.com/sebastianfeldmann/git
20
 * @since   Class available since Release 3.2.0
21
 */
22
class Xml
23
{
24
    /**
25
     * XML commit format to parse the git log as xml
26
     *
27
     * @var string
28
     */
29
    public const FORMAT = '<commit>%n' .
30
                            '<hash>%h</hash>%n' .
31
                            '<names><![CDATA[%d]]></names>%n' .
32
                            '<date>%ci</date>%n' .
33
                            '<author><![CDATA[%an]]></author>%n' .
34
                            '<subject><![CDATA[%s]]></subject>%n' .
35
                            '<body><![CDATA[%n%b%n]]></body>%n' .
36
                          '</commit>';
37
38
    /**
39
     * Parse log output into list of Commit objects
40
     *
41
     * @param  string $output
42
     * @return array<\SebastianFeldmann\Git\Log\Commit>
43
     * @throws \Exception
44
     */
45 3
    public static function parseLogOutput(string $output): array
46
    {
47 3
        $log = [];
48 3
        $xml = '<?xml version="1.0"?><log>' . $output . '</log>';
49
50 3
        $parsedXML = \simplexml_load_string($xml);
51
52 3
        foreach ($parsedXML->commit as $commitXML) {
53 3
            $nameRaw = str_replace(['(', ')'], '', trim((string) $commitXML->names));
54 3
            $names   = empty($nameRaw) ? [] : array_map('trim', explode(',', $nameRaw));
55
56 3
            $log[]   = new Commit(
57 3
                trim((string) $commitXML->hash),
58 3
                $names,
59 3
                trim((string) $commitXML->subject),
60 3
                trim((string) $commitXML->body),
61 3
                new \DateTimeImmutable(trim((string) $commitXML->date)),
62 3
                trim((string) $commitXML->author)
63
            );
64
        }
65 3
        return $log;
66
    }
67
}
68