Xml::parseLogOutput()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

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