ImageName::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines\File;
6
7
/**
8
 * image name parser and value object
9
 */
10
class ImageName
11
{
12
    /**
13
     * @var string
14
     */
15
    private $name;
16
17
    /**
18
     * validate image name
19
     *
20
     * Is a Docker image name (optionally with a tag or digest)
21
     * syntactically valid?
22
     *
23
     * @see doc/DOCKER-NAME-TAG.md
24
     *
25
     * @param string $name of docker image
26
     *
27
     * @return bool
28
     */
29 12
    public static function validate($name)
30
    {
31 12
        $pattern
32
            = '{^'
33
            . '([a-zA-Z0-9.-]+(:[0-9]+)?/)?' # prefix
34
            . '([a-z0-9]+(?:(?:\.|__?|-+)[a-z0-9]+)*)(/[a-z0-9]+(?:(?:\.|__?|-+)[a-z0-9]+)*)*' # name-components
35
            . '(:[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}|@[a-z0-9]+([+._-][a-z0-9]+)*:[a-zA-Z0-9=_-]+)?' # ":" tag-name | "@" digest
36
            . '$}';
37
38 12
        $result = preg_match($pattern, $name);
39
40 12
        return 1 === $result;
41
    }
42
43
    /**
44
     * @param string $name
45
     *
46
     * @throws ParseException
47
     */
48 3
    public function __construct($name)
49
    {
50 3
        $this->parse($name);
51
    }
52
53 1
    public function __toString()
54
    {
55 1
        return $this->name;
56
    }
57
58
    /**
59
     * @param string $name
60
     *
61
     * @throws ParseException
62
     *
63
     * @return void
64
     */
65 3
    private function parse($name)
66
    {
67 3
        if (!self::validate($name)) {
68 1
            throw new ParseException(sprintf(
69
                "'image' invalid Docker image name: '%s'",
70
                $name
71
            ));
72
        }
73
74 2
        $this->name = (string)$name;
75
    }
76
}
77