Completed
Push — v2 ( 3b3087...c6f6d7 )
by Joschi
04:41
created

Item::exportPropertyValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
rs 9.4285
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\Item\ItemInterface as ApplicationItemInterface;
41
use Jkphl\Micrometa\Domain\Exceptions\OutOfBoundsException as DomainOutOfBoundsException;
42
use Jkphl\Micrometa\Infrastructure\Factory\ItemFactory;
43
use Jkphl\Micrometa\Infrastructure\Factory\ProfiledNamesFactory;
44
use Jkphl\Micrometa\Infrastructure\Parser\ProfiledNamesList;
45
use Jkphl\Micrometa\Ports\Exceptions\InvalidArgumentException;
46
use Jkphl\Micrometa\Ports\Exceptions\OutOfBoundsException;
47
48
/**
49
 * Micro information item
50
 *
51
 * @package Jkphl\Micrometa
52
 * @subpackage Jkphl\Micrometa\Ports
53
 */
54
class Item extends ItemList implements ItemInterface
55
{
56
    /**
57
     * Application item
58
     *
59
     * @var ApplicationItemInterface
60
     */
61
    protected $item;
62
63
    /**
64
     * Item constructor
65
     *
66
     * @param ApplicationItemInterface $item Application item
67
     */
68 8
    public function __construct(ApplicationItemInterface $item)
69
    {
70 8
        $this->item = $item;
71 8
        parent::__construct(ItemFactory::createFromApplicationItems($this->item->getChildren()));
72 8
    }
73
74
    /**
75
     * Get the first value of an item property
76
     *
77
     * @param string $name Item property name
78
     * @return string First value of an item property
79
     * @api
80
     */
81 1
    public function __get($name)
82
    {
83 1
        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...
84
    }
85
86
    /**
87
     * Get a single property (value)
88
     *
89
     * @param string $name Property name
90
     * @param string $profile Property profile
91
     * @param int $index Property value index
92
     * @return array|string|ItemInterface Property value(s)
93
     * @throws OutOfBoundsException If the property name is unknown
94
     * @throws OutOfBoundsException If the property value index is out of bounds
95
     * @api
96
     */
97 5
    public function getProperty($name, $profile = null, $index = null)
98
    {
99
        try {
100 5
            $propertyValues = $this->item->getProperty($name, $profile);
101 4
        } catch (DomainOutOfBoundsException $e) {
102 4
            throw new OutOfBoundsException($e->getMessage(), $e->getCode());
103
        }
104
105
        // If all property values should be returned
106 5
        if ($index === null) {
107 5
            return array_map([$this, 'exportPropertyValue'], $propertyValues);
108
        }
109
110
        // If the property value index is out of bounds
111 4
        if (!isset($propertyValues[$index])) {
112
            throw new OutOfBoundsException(
113
                sprintf(OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX_STR, $index),
114
                OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX
115
            );
116
        }
117
118 4
        return $this->exportPropertyValue($propertyValues[$index]);
119
    }
120
121
    /**
122
     * Prepare a property value for returning it
123
     *
124
     * @param ValueInterface $value Property value
125
     * @return Item|mixed Returnable property value
126
     */
127 5
    protected function exportPropertyValue(ValueInterface $value)
128
    {
129 5
        return ($value instanceof ApplicationItemInterface) ?
130 5
            ItemFactory::createFromApplicationItem($value) : $value->export();
131
    }
132
133
    /**
134
     * Return whether the item is of a particular type (or contained in a list of types)
135
     *
136
     * The item type(s) can be specified in a variety of ways, @see ProfiledNamesFactory::createFromArguments()
137
     *
138
     * @param string $name Name
139
     * @param string|null $profile Profile
140
     * @return boolean Item type is contained in the list of types
141
     * @api
142
     */
143 2
    public function isOfType($name, $profile = null)
144
    {
145
        /** @var ProfiledNamesList $types */
146 2
        $types = ProfiledNamesFactory::createFromArguments(func_get_args());
147
148
        // Run through all item types
149
        /** @var \stdClass $itemType */
150 2
        foreach ($this->item->getType() as $itemType) {
151
            // Run through all query types
152
            /** @var \stdClass $queryType */
153 2
            foreach ($types as $queryType) {
154 2
                if (($queryType->name == $itemType->name) &&
155 2
                    (($queryType->profile === null) ? true : ($queryType->profile == $itemType->profile))
156
                ) {
157
                    // TODO: Type aliasing
158 2
                    return true;
159
                }
160
            }
161
        }
162
163
        return false;
164
    }
165
166
    /**
167
     * Get all values of the first available property in a stack
168
     *
169
     * The property stack can be specified in a variety of ways, @see ProfiledNamesFactory::createFromArguments()
170
     *
171
     * @param string $name Name
172
     * @param string $profile Profile
173
     * @return array Property values
174
     * @throws InvalidArgumentException If no property name was given
175
     * @throws OutOfBoundsException If none of the requested properties is known
176
     * @api
177
     */
178 2
    public function getFirstProperty($name, $profile = null)
179
    {
180
        /** @var ProfiledNamesList $properties */
181 2
        $properties = ProfiledNamesFactory::createFromArguments(func_get_args());
182
183
        // Prepare a default exception
184 2
        $e = new OutOfBoundsException(
185 2
            OutOfBoundsException::NO_MATCHING_PROPERTIES_STR,
186 2
            OutOfBoundsException::NO_MATCHING_PROPERTIES
187
        );
188
189
        // Run through all properties
190 2
        foreach ($properties as $property) {
191
            try {
192 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...
193 1
            } catch (OutOfBoundsException $e) {
194 1
                continue;
195
            }
196
        }
197
198 1
        throw $e;
199
    }
200
201
    /**
202
     * Return all properties
203
     *
204
     * @return array[] Properties
205
     * @api
206
     */
207
    public function getProperties()
208
    {
209
        return $this->item->getProperties()->export();
210
    }
211
212
    /**
213
     * Return an object representation of the item
214
     *
215
     * @return \stdClass Micro information item
216
     * @api
217
     */
218
    public function toObject()
219
    {
220
        return $this->item->export();
221
    }
222
}
223