Completed
Push — develop ( a3c683...8c914c )
by Stuart
02:11
created

ParseInet6Address::fromTraversable()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 8.8571
cc 2
eloc 13
nc 2
nop 1
1
<?php
2
3
/**
4
 * Copyright (c) 2016-present Ganbaro Digital Ltd
5
 * All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or without
8
 * modification, are permitted provided that the following conditions
9
 * are met:
10
 *
11
 *   * Redistributions of source code must retain the above copyright
12
 *     notice, this list of conditions and the following disclaimer.
13
 *
14
 *   * Redistributions in binary form must reproduce the above copyright
15
 *     notice, this list of conditions and the following disclaimer in
16
 *     the documentation and/or other materials provided with the
17
 *     distribution.
18
 *
19
 *   * Neither the names of the copyright holders nor the names of his
20
 *     contributors may be used to endorse or promote products derived
21
 *     from this software without specific prior written permission.
22
 *
23
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34
 * POSSIBILITY OF SUCH DAMAGE.
35
 *
36
 * @category  Libraries
37
 * @package   OperatingSystem/NetInterface/Parsers
38
 * @author    Stuart Herbert <[email protected]>
39
 * @copyright 2016-present Ganbaro Digital Ltd www.ganbarodigital.com
40
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
41
 * @link      http://code.ganbarodigital.com/php-array-tools
42
 */
43
44
namespace GanbaroDigital\OperatingSystem\IpRoute\Parsers;
45
46
use GanbaroDigital\ArrayTools\Parsers\ConvertKeyValuePairsToArray;
47
use GanbaroDigital\ArrayTools\Filters\ExtractFirstItem;
48
use GanbaroDigital\ArrayTools\ValueBuilders\ConvertToArray;
49
use GanbaroDigital\OperatingSystem\Exceptions\E4xx_CannotParseInet6AddressLine;
50
use GanbaroDigital\OperatingSystem\Exceptions\E4xx_UnsupportedType;
51
use GanbaroDigital\OperatingSystem\NetInterfaces\Values\Inet6Address;
52
use GanbaroDigital\Reflection\Maps\MapTypeToMethod;
53
use GanbaroDigital\Reflection\ValueBuilders\SimpleType;
54
55
class ParseInet6Address
56
{
57
    /**
58
     * parse an inet6 (IPv6) address block from the output of 'ip addr show'
59
     *
60
     * @param  mixed $inet6Lines
61
     *         the line(s) to parse
62
     * @return Inet6Address
63
     *         the inet address defined in the output
64
     */
65
    public function __invoke($inet6Lines)
66
    {
67
        return self::from($inet6Lines);
68
    }
69
70
    public static function from($inet6Lines)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
71
    {
72
        $method = MapTypeToMethod::using($inet6Lines, self::$dispatchMap);
73
        return self::$method($inet6Lines);
74
    }
75
76
    /**
77
     * a map of which types we support, and how to process them
78
     * @var array
79
     */
80
    private static $dispatchMap = [
81
        "String" => "fromString",
82
        "Traversable" => "fromTraversable",
83
    ];
84
85
    /**
86
     * called when we've been given a data type that we do not support
87
     *
88
     * @param  mixed $output
89
     *         the unsupported data
90
     * @return void
91
     * @throws E4xx_UnsupportedType
92
     */
93
    private static function nothingMatchesTheInputType($output)
94
    {
95
        throw new E4xx_UnsupportedType(SimpleType::from($output));
96
    }
97
98
    /**
99
     * parse an inet6 (IPv6) address block from the output of 'ip addr show'
100
     *
101
     * @param  string $inet6Lines
102
     *         the line(s) to parse
103
     * @return InetAddress
0 ignored issues
show
Documentation introduced by
Should the return type not be Inet6Address?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
104
     *         the inet address defined in the output
105
     */
106
    private static function fromString($inet6Lines)
107
    {
108
        $lines = explode("\n", $inet6Lines);
109
110
        return self::fromTraversable($lines);
111
    }
112
113
    /**
114
     * parse an inet6 (IPv6) address block from the output of 'ip addr show'
115
     *
116
     * @param  array|Traversable $inet6Lines
117
     *         the line(s) to parse
118
     * @return InetAddress
0 ignored issues
show
Documentation introduced by
Should the return type not be Inet6Address?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
119
     *         the inet address defined in the output
120
     */
121
    private static function fromTraversable($inet6Lines)
122
    {
123
        // we want a real PHP array for this
124
        $inet6Lines = ConvertToArray::from($inet6Lines);
125
126
        // line 0 is the inet line itself
127
        $inet6Details = self::parseFirstLine(array_shift($inet6Lines));
128
129
        // if there is a line 1, it contains additional flags
130
        while (!empty($inet6Lines)) {
131
            $inet6Details['properties'] = array_merge(self::parseSecondLine(array_shift($inet6Lines)), $inet6Details['properties']);
132
        }
133
134
        // now to convert this into an InetAddress value
135
        $retval = new Inet6Address(
136
            $inet6Details['address'],
137
            $inet6Details['netmask'],
138
            $inet6Details['scope'],
139
            $inet6Details['addressLabel'],
140
            $inet6Details['linkDevice'],
141
            $inet6Details['properties']
142
        );
143
144
        // all done
145
        return $retval;
146
    }
147
148
    /**
149
     * extract data from the first line of the inet address definition
150
     *
151
     * @param  string $line
152
     *         the line to parse
153
     * @return array
154
     *         the extracted data
155
     */
156
    private static function parseFirstLine($line)
157
    {
158
        $regex = "~inet6 (?<addr>.+)(?<netmask>/[0-9]{1,5})( scope (?<scope>[a-z]+)){0,1}( (?<addressLabel>secondary|dynamic|deprecated|tentative)){0,1}( (?<linkDevice>.*)){0,1}$~";
159
        $matches = [];
160
        if (!preg_match_all($regex, $line, $matches)) {
161
            throw new E4xx_CannotParseInet6AddressLine($line);
162
        }
163
164
        return [
165
            'address' => $matches['addr'][0],
166
            'netmask' => $matches['netmask'][0],
167
            'scope' => ExtractFirstItem::from($matches['scope'], null),
168
            'addressLabel' => ExtractFirstItem::from($matches['addressLabel'], null),
169
            'linkDevice' => ExtractFirstItem::from($matches['linkDevice'], null),
170
            'properties' => [],
171
        ];
172
    }
173
174
    /**
175
     * extract data from the second line of the inet address definition
176
     *
177
     * @param  string $line
178
     *         the line to parse
179
     * @return array
180
     *         the extracted data, as key/value pairs
181
     */
182
    private static function parseSecondLine($line)
183
    {
184
        return ConvertKeyValuePairsToArray::from($line, ' ', ' ');
185
    }
186
}
187