Completed
Push — master ( 3071de...f5f5ef )
by Bernhard
02:13
created

SchemaUriVersioner::parseVersion()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 18
ccs 9
cts 9
cp 1
rs 9.4285
cc 3
eloc 10
nc 3
nop 1
crap 3
1
<?php
2
3
/*
4
 * This file is part of the webmozart/json package.
5
 *
6
 * (c) Bernhard Schussek <[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 Webmozart\Json\Versioning;
13
14
use stdClass;
15
16
/**
17
 * Expects the version to be set in the "$schema" field of a JSON object.
18
 *
19
 * @since  1.3
20
 *
21
 * @author Bernhard Schussek <[email protected]>
22
 */
23
class SchemaUriVersioner implements JsonVersioner
24
{
25
    /**
26
     * The default pattern used to extract the version of a schema ID.
27
     */
28
    const DEFAULT_PATTERN = '~(?<=/)\d+\.\d+(?=/)~';
29
30
    /**
31
     * @var string
32
     */
33
    private $pattern;
34
35 10
    public function __construct($pattern = self::DEFAULT_PATTERN)
36
    {
37 10
        $this->pattern = $pattern;
38 10
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 4
    public function parseVersion(stdClass $jsonData)
44
    {
45 4
        if (!isset($jsonData->{'$schema'})) {
46 1
            throw new CannotParseVersionException('Cannot find "$schema" property in JSON object.');
47
        }
48
49 3
        $schema = $jsonData->{'$schema'};
50
51 3
        if (!preg_match($this->pattern, $schema, $matches)) {
52 1
            throw new CannotParseVersionException(sprintf(
53 1
                'Cannot find version of schema "%s" (pattern: "%s")',
54
                $schema,
55 1
                $this->pattern
56
            ));
57
        }
58
59 2
        return $matches[0];
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 6
    public function updateVersion(stdClass $jsonData, $version)
66
    {
67 6
        if (!isset($jsonData->{'$schema'})) {
68 1
            throw new CannotUpdateVersionException('Cannot find "$schema" property in JSON object.');
69
        }
70
71 5
        $previousSchema = $jsonData->{'$schema'};
72 5
        $newSchema = preg_replace($this->pattern, $version, $previousSchema, -1, $count);
73
74 5
        if (1 !== $count) {
75 2
            throw new CannotUpdateVersionException(sprintf(
76 2
                'Cannot update version of schema "%s" (pattern: "%s"): %s',
77
                $previousSchema,
78 2
                $this->pattern,
79 2
                $count < 1 ? 'Not found' : 'Found more than once'
80
            ));
81
        }
82
83 3
        $jsonData->{'$schema'} = $newSchema;
84 3
    }
85
}
86