Completed
Push — v2 ( e198fb...470733 )
by Joschi
04:46
created

Item::getFormat()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
/**
4
 * micrometa
5
 *
6
 * @category Jkphl
7
 * @package Jkphl\Micrometa
8
 * @subpackage Jkphl\Micrometa\Ports
9
 * @author Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright Copyright © 2017 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2017 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Jkphl\Micrometa\Ports\Item;
38
39
use Jkphl\Micrometa\Application\Contract\ValueInterface;
40
use Jkphl\Micrometa\Application\Factory\AliasFactory;
41
use Jkphl\Micrometa\Application\Item\ItemInterface as ApplicationItemInterface;
42
use Jkphl\Micrometa\Domain\Exceptions\OutOfBoundsException as DomainOutOfBoundsException;
43
use Jkphl\Micrometa\Infrastructure\Factory\ItemFactory;
44
use Jkphl\Micrometa\Infrastructure\Factory\ProfiledNamesFactory;
45
use Jkphl\Micrometa\Infrastructure\Parser\ProfiledNamesList;
46
use Jkphl\Micrometa\Ports\Exceptions\InvalidArgumentException;
47
use Jkphl\Micrometa\Ports\Exceptions\OutOfBoundsException;
48
49
/**
50
 * Micro information item
51
 *
52
 * @package Jkphl\Micrometa
53
 * @subpackage Jkphl\Micrometa\Ports
54
 */
55
class Item extends ItemList implements ItemInterface
56
{
57
    /**
58
     * Application item
59
     *
60
     * @var ApplicationItemInterface
61
     */
62
    protected $item;
63
64
    /**
65
     * Item constructor
66
     *
67
     * @param ApplicationItemInterface $item Application item
68
     */
69 13
    public function __construct(ApplicationItemInterface $item)
70
    {
71 13
        $this->item = $item;
72 13
        parent::__construct(ItemFactory::createFromApplicationItems($this->item->getChildren()));
73 13
    }
74
75
    /**
76
     * Get the first value of an item property
77
     *
78
     * @param string $name Item property name
79
     * @return string First value of an item property
80
     * @api
81
     */
82 2
    public function __get($name)
83
    {
84 2
        return $this->getProperty($name, null, 0);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getProperty($name, null, 0); (array|string|Jkphl\Micro...orts\Item\ItemInterface) is incompatible with the return type declared by the interface Jkphl\Micrometa\Ports\Item\ItemInterface::__get of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
85
    }
86
87
    /**
88
     * Get a single property (value)
89
     *
90
     * @param string $name Property name
91
     * @param string $profile Property profile
92
     * @param int $index Property value index
93
     * @return array|string|ItemInterface Property value(s)
94
     * @throws OutOfBoundsException If the property name is unknown
95
     * @throws OutOfBoundsException If the property value index is out of bounds
96
     * @api
97
     */
98 7
    public function getProperty($name, $profile = null, $index = null)
99
    {
100
        try {
101 7
            $propertyValues = $this->item->getProperty($name, $profile);
102 4
        } catch (DomainOutOfBoundsException $e) {
103 4
            throw new OutOfBoundsException($e->getMessage(), $e->getCode());
104
        }
105
106
        // If all property values should be returned
107 7
        if ($index === null) {
108 5
            return array_map([$this, 'exportPropertyValue'], $propertyValues);
109
        }
110
111
        // If the property value index is out of bounds
112 6
        if (!isset($propertyValues[$index])) {
113 1
            throw new OutOfBoundsException(
114 1
                sprintf(OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX_STR, $index),
115 1
                OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX
116
            );
117
        }
118
119 5
        return $this->exportPropertyValue($propertyValues[$index]);
120
    }
121
122
    /**
123
     * Prepare a property value for returning it
124
     *
125
     * @param ValueInterface $value Property value
126
     * @return Item|mixed Returnable property value
127
     */
128 6
    protected function exportPropertyValue(ValueInterface $value)
129
    {
130 6
        return ($value instanceof ApplicationItemInterface) ?
131 6
            ItemFactory::createFromApplicationItem($value) : $value->export();
132
    }
133
134
    /**
135
     * Return whether the item is of a particular type (or contained in a list of types)
136
     *
137
     * The item type(s) can be specified in a variety of ways, @see ProfiledNamesFactory::createFromArguments()
138
     *
139
     * @param string $name Name
140
     * @param string|null $profile Profile
141
     * @return boolean Item type is contained in the list of types
142
     * @api
143
     */
144 5
    public function isOfType($name, $profile = null)
145
    {
146
        /** @var ProfiledNamesList $types */
147 5
        $types = ProfiledNamesFactory::createFromArguments(func_get_args());
148 5
        $aliasFactory = new AliasFactory();
149
150
        // Run through all item types
151
        /** @var \stdClass $itemType */
152 5
        foreach ($this->item->getType() as $itemType) {
153 5
            $itemTypeNames = $aliasFactory->createAliases($itemType->name);
154 5
            if ($this->isOfProfiledTypes($itemType->profile, $itemTypeNames, $types)) {
155 5
                return true;
156
            }
157
        }
158
159 3
        return false;
160
    }
161
162
    /**
163
     * Return whether an aliased item type in contained in a set of query types
164
     *
165
     * @param string $profile Type profile
166
     * @param array $names Aliased type names
167
     * @param ProfiledNamesList $types Query types
168
     * @return bool Item type is contained in the set of query types
169
     */
170 5
    protected function isOfProfiledTypes($profile, array $names, ProfiledNamesList $types)
171
    {
172
        // Run through all query types
173
        /** @var \stdClass $queryType */
174 5
        foreach ($types as $queryType) {
175 5
            if (in_array($queryType->name, $names) &&
176 5
                (($queryType->profile === null) ? true : ($queryType->profile == $profile))
177
            ) {
178 5
                return true;
179
            }
180
        }
181 3
        return false;
182
    }
183
184
    /**
185
     * Get all values of the first available property in a stack
186
     *
187
     * The property stack can be specified in a variety of ways, @see ProfiledNamesFactory::createFromArguments()
188
     *
189
     * @param string $name Name
190
     * @param string $profile Profile
191
     * @return array Property values
192
     * @throws InvalidArgumentException If no property name was given
193
     * @throws OutOfBoundsException If none of the requested properties is known
194
     * @api
195
     */
196 2
    public function getFirstProperty($name, $profile = null)
197
    {
198
        /** @var ProfiledNamesList $properties */
199 2
        $properties = ProfiledNamesFactory::createFromArguments(func_get_args());
200
201
        // Prepare a default exception
202 2
        $e = new OutOfBoundsException(
203 2
            OutOfBoundsException::NO_MATCHING_PROPERTIES_STR,
204 2
            OutOfBoundsException::NO_MATCHING_PROPERTIES
205
        );
206
207
        // Run through all properties
208 2
        foreach ($properties as $property) {
209
            try {
210 2
                return $this->getProperty($property->name, $property->profile);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getPropert...e, $property->profile); (array|string|Jkphl\Micro...orts\Item\ItemInterface) is incompatible with the return type declared by the interface Jkphl\Micrometa\Ports\It...rface::getFirstProperty of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
211 1
            } catch (OutOfBoundsException $e) {
212 1
                continue;
213
            }
214
        }
215
216 1
        throw $e;
217
    }
218
219
    /**
220
     * Return all properties
221
     *
222
     * @return array[] Properties
223
     * @api
224
     */
225 1
    public function getProperties()
226
    {
227 1
        return $this->item->getProperties()->export();
228
    }
229
230
    /**
231
     * Return an object representation of the item
232
     *
233
     * @return \stdClass Micro information item
234
     * @api
235
     */
236 2
    public function toObject()
237
    {
238 2
        return $this->item->export();
239
    }
240
241
    /**
242
     * Get the item type
243
     *
244
     * @return \stdClass[] Item type
245
     */
246 1
    public function getType()
247
    {
248 1
        return $this->item->getType();
249
    }
250
251
    /**
252
     * Get the item format
253
     *
254
     * @return int Item format
255
     */
256 1
    public function getFormat()
257
    {
258 1
        return $this->item->getFormat();
259
    }
260
}
261