ParseInet6Address::parseSecondLine()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
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
    /**
71
     * parse an inet6 (IPv6) address block from the output of 'ip addr show'
72
     *
73
     * @param  mixed $inet6Lines
74
     *         the line(s) to parse
75
     * @return Inet6Address
76
     *         the inet address defined in the output
77
     */
78
    public static function from($inet6Lines)
79
    {
80
        $method = MapTypeToMethod::using($inet6Lines, self::$dispatchMap);
81
        return self::$method($inet6Lines);
82
    }
83
84
    /**
85
     * a map of which types we support, and how to process them
86
     * @var array
87
     */
88
    private static $dispatchMap = [
89
        "String" => "fromString",
90
        "Traversable" => "fromTraversable",
91
    ];
92
93
    /**
94
     * called when we've been given a data type that we do not support
95
     *
96
     * @param  mixed $output
97
     *         the unsupported data
98
     * @return void
99
     * @throws E4xx_UnsupportedType
100
     */
101
    private static function nothingMatchesTheInputType($output)
102
    {
103
        throw new E4xx_UnsupportedType(SimpleType::from($output));
104
    }
105
106
    /**
107
     * parse an inet6 (IPv6) address block from the output of 'ip addr show'
108
     *
109
     * @param  string $inet6Lines
110
     *         the line(s) to parse
111
     * @return Inet6Address
112
     *         the inet address defined in the output
113
     */
114
    private static function fromString($inet6Lines)
115
    {
116
        $lines = explode("\n", $inet6Lines);
117
118
        return self::fromTraversable($lines);
119
    }
120
121
    /**
122
     * parse an inet6 (IPv6) address block from the output of 'ip addr show'
123
     *
124
     * @param  array|Traversable $inet6Lines
125
     *         the line(s) to parse
126
     * @return Inet6Address
127
     *         the inet address defined in the output
128
     */
129
    private static function fromTraversable($inet6Lines)
130
    {
131
        // we want a real PHP array for this
132
        $inet6Lines = ConvertToArray::from($inet6Lines);
133
134
        // line 0 is the inet line itself
135
        $inet6Details = self::parseFirstLine(array_shift($inet6Lines));
136
137
        // if there is a line 1, it contains additional flags
138
        while (!empty($inet6Lines)) {
139
            $inet6Details['properties'] = array_merge(self::parseSecondLine(array_shift($inet6Lines)), $inet6Details['properties']);
140
        }
141
142
        // now to convert this into an InetAddress value
143
        $retval = new Inet6Address(
144
            $inet6Details['address'],
145
            $inet6Details['netmask'],
146
            $inet6Details['scope'],
147
            $inet6Details['addressLabel'],
148
            $inet6Details['linkDevice'],
149
            $inet6Details['properties']
150
        );
151
152
        // all done
153
        return $retval;
154
    }
155
156
    /**
157
     * extract data from the first line of the inet address definition
158
     *
159
     * @param  string $line
160
     *         the line to parse
161
     * @return array
162
     *         the extracted data
163
     */
164
    private static function parseFirstLine($line)
165
    {
166
        $regex = "~inet6 (?<addr>.+)(?<netmask>/[0-9]{1,5})( scope (?<scope>[a-z]+)){0,1}( (?<addressLabel>secondary|dynamic|deprecated|tentative)){0,1}( (?<linkDevice>.*)){0,1}$~";
167
        $matches = [];
168
        if (!preg_match_all($regex, $line, $matches)) {
169
            throw new E4xx_CannotParseInet6AddressLine($line);
170
        }
171
172
        return [
173
            'address' => $matches['addr'][0],
174
            'netmask' => $matches['netmask'][0],
175
            'scope' => ExtractFirstItem::from($matches['scope'], null),
176
            'addressLabel' => ExtractFirstItem::from($matches['addressLabel'], null),
177
            'linkDevice' => ExtractFirstItem::from($matches['linkDevice'], null),
178
            'properties' => [],
179
        ];
180
    }
181
182
    /**
183
     * extract data from the second line of the inet address definition
184
     *
185
     * @param  string $line
186
     *         the line to parse
187
     * @return array
188
     *         the extracted data, as key/value pairs
189
     */
190
    private static function parseSecondLine($line)
191
    {
192
        return ConvertKeyValuePairsToArray::from($line, ' ', ' ');
193
    }
194
}
195