Completed
Push — master ( e82759...2ca52b )
by Joschi
05:55
created

RelationFactory::createFromString()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.243

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 16
ccs 7
cts 10
cp 0.7
crap 3.243
rs 9.4285
1
<?php
2
3
/**
4
 * apparat-object
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Object
8
 * @subpackage  Apparat\Object\<Layer>
9
 * @author      Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright   Copyright © 2016 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 © 2016 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 Apparat\Object\Domain\Factory;
38
39
use Apparat\Kernel\Ports\Kernel;
40
use Apparat\Object\Domain\Model\Path\ApparatInvalidArgumentException;
41
use Apparat\Object\Domain\Model\Path\ApparatUrl;
42
use Apparat\Object\Domain\Model\Path\Url;
43
use Apparat\Object\Domain\Model\Relation\ContributedByRelation;
44
use Apparat\Object\Domain\Model\Relation\ContributesRelation;
45
use Apparat\Object\Domain\Model\Relation\EmbeddedRelation;
46
use Apparat\Object\Domain\Model\Relation\EmbedsRelation;
47
use Apparat\Object\Domain\Model\Relation\InvalidArgumentException;
48
use Apparat\Object\Domain\Model\Relation\LikedByRelation;
49
use Apparat\Object\Domain\Model\Relation\LikesRelation;
50
use Apparat\Object\Domain\Model\Relation\OutOfBoundsException;
51
use Apparat\Object\Domain\Model\Relation\ReferredByRelation;
52
use Apparat\Object\Domain\Model\Relation\RefersToRelation;
53
use Apparat\Object\Domain\Model\Relation\RelationInterface;
54
use Apparat\Object\Domain\Model\Relation\RepliedByRelation;
55
use Apparat\Object\Domain\Model\Relation\RepliesToRelation;
56
use Apparat\Object\Domain\Model\Relation\RepostedByRelation;
57
use Apparat\Object\Domain\Model\Relation\RepostsRelation;
58
use Apparat\Object\Domain\Repository\RepositoryInterface;
59
use Apparat\Object\Infrastructure\Utilities\Validator;
60
61
/**
62
 * Relation factory
63
 *
64
 * @package Apparat\Object
65
 * @subpackage Apparat\Object\Domain
66
 */
67
class RelationFactory
68
{
69
    /**
70
     * URL component key
71
     *
72
     * @string
73
     */
74
    const PARSE_URL = 'url';
75
    /**
76
     * Label component key
77
     *
78
     * @string
79
     */
80
    const PARSE_LABEL = 'label';
81
    /**
82
     * Email component key
83
     *
84
     * @string
85
     */
86
    const PARSE_EMAIL = 'email';
87
    /**
88
     * Component relation coupling
89
     *
90
     * @string
91
     */
92
    const PARSE_COUPLING = 'coupling';
93
    /**
94
     * Relation types
95
     *
96
     * @var array
97
     */
98
    public static $relationTypes = [
99
        ContributesRelation::TYPE => ContributesRelation::class,
100
        ContributedByRelation::TYPE => ContributedByRelation::class,
101
        EmbedsRelation::TYPE => EmbedsRelation::class,
102
        EmbeddedRelation::TYPE => EmbeddedRelation::class,
103
        LikesRelation::TYPE => LikesRelation::class,
104
        LikedByRelation::TYPE => LikedByRelation::class,
105
        RefersToRelation::TYPE => RefersToRelation::class,
106
        ReferredByRelation::TYPE => ReferredByRelation::class,
107
        RepliesToRelation::TYPE => RepliesToRelation::class,
108
        RepliedByRelation::TYPE => RepliedByRelation::class,
109
        RepostsRelation::TYPE => RepostsRelation::class,
110
        RepostedByRelation::TYPE => RepostedByRelation::class,
111
    ];
112
113
    /**
114
     * Parse a relation serialization and instantiate the relation
115
     *
116
     * @param string $relationType Relation type
117
     * @param string $relation Relation serialization
118
     * @param RepositoryInterface $contextRepository Context repository
119
     * @return RelationInterface Relation object
120
     * @throws InvalidArgumentException If the relation format is invalid
121
     */
122 14
    public static function createFromString($relationType, $relation, RepositoryInterface $contextRepository)
123
    {
124
        // If the relation type is invalid
125 14
        if (empty($relationType) || empty(self::$relationTypes[$relationType])) {
126
            throw new OutOfBoundsException(
127
                sprintf('Invalid object relation type "%s"', $relationType),
128
                OutOfBoundsException::INVALID_OBJECT_RELATION_TYPE
129
            );
130
        }
131
132 14
        $relationParams = self::parseRelationString($relation, $contextRepository);
133 14
        return Kernel::create(
134 14
            self::$relationTypes[$relationType],
135 14
            array_values($relationParams)
136 14
        );
137
    }
138
139
    /**
140
     * Parse a relation serialization and instantiate the relation object
141
     *
142
     * @param string $relation Relation serialization
143
     * @param RepositoryInterface $contextRepository Context repository
144
     * @return array Parsed relation components
145
     */
146 14
    protected static function parseRelationString($relation, RepositoryInterface $contextRepository)
147
    {
148
        // TODO: Document exceptions
149
        $parsed = [
150 14
            self::PARSE_URL => null,
151 14
            self::PARSE_LABEL => null,
152 14
            self::PARSE_EMAIL => null,
153 14
            self::PARSE_COUPLING => RelationInterface::LOOSE_COUPLING,
154 14
        ];
155
156
        // Split the relation string and parse the components
157 14
        foreach (preg_split('%\s+%', $relation) as $relationComponent) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
158
159
            // If it's an email component
160 14
            if (!strncmp('<', $relationComponent, 1)) {
161
                // If an email component has already been matched
162
                if (!empty($parsed[self::PARSE_EMAIL])) {
163
                    throw new InvalidArgumentException(
164
                        sprintf('Repeated relation email component "%s" not allowed', self::PARSE_EMAIL),
165
                        InvalidArgumentException::REPEATED_RELATION_COMPONENT_NOT_ALLOWED
166
                    );
167
                }
168
169
                $parsed[self::PARSE_EMAIL] = self::parseRelationEmail($relationComponent);
170
                continue;
171
            }
172
173
            // Next: Try to parse it as URL
174
            try {
175 14
                $url = self::parseRelationUrl($relationComponent, $parsed[self::PARSE_COUPLING], $contextRepository);
0 ignored issues
show
Documentation introduced by
$parsed[self::PARSE_COUPLING] is of type null|string|object<Appar...\Domain\Model\Path\Url>, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
176
177
                // If an email component has already been matched
178 14
                if (!empty($parsed[self::PARSE_URL])) {
179
                    throw new InvalidArgumentException(
180
                        sprintf('Repeated relation url component "%s" not allowed', self::PARSE_URL),
181
                        InvalidArgumentException::REPEATED_RELATION_COMPONENT_NOT_ALLOWED
182
                    );
183
                }
184
185 14
                $parsed[self::PARSE_URL] = $url;
186
187
                // Else: Process as label component
188 14
            } catch (\Exception $e) {
189 14
                $parsed[self::PARSE_LABEL] = trim($parsed[self::PARSE_LABEL].' '.$relationComponent);
190
            }
191 14
        }
192
193 14
        return $parsed;
194
    }
195
196
    /**
197
     * Parse and validate a relation email address component
198
     *
199
     * @param string $relationEmail Email address
200
     * @return string Valid email address
201
     * @throws InvalidArgumentException If the email address is invalid
202
     */
203
    protected static function parseRelationEmail($relationEmail)
204
    {
205
        // If it's a valid email address
206
        if (preg_match('%^\<(.+)\>$%', $relationEmail, $emailAddress) && Validator::isEmail($emailAddress[1])) {
207
            return $emailAddress[1];
208
        }
209
210
        throw new InvalidArgumentException(
211
            sprintf('Invalid relation email address "%s"', $relationEmail),
212
            InvalidArgumentException::INVALID_RELATION_EMAIL_ADDRESS
213
        );
214
    }
215
216
    /**
217
     * Parse and instantiate a relation URL
218
     *
219
     * @param string $url URL
220
     * @param boolean $coupling Strong coupling
221
     * @param RepositoryInterface $contextRepository Context repository
222
     * @return Url URL
223
     */
224 14
    protected static function parseRelationUrl($url, &$coupling, RepositoryInterface $contextRepository)
225
    {
226 14
        if (strlen($url)) {
227
            // If the URL requires tight coupling
228 14
            if (!strncmp('!', $url, 1)) {
229
                $coupling = RelationInterface::TIGHT_COUPLING;
230
                $url = substr($url, 1);
231
            }
232
233
            // Try to instantiate as an apparat URL
234
            try {
235 14
                return Kernel::create(ApparatUrl::class, [$url, true, $contextRepository]);
236
237
                // If there's an apparat URL problem: Try to instantiate as a regular URL
238 14
            } catch (ApparatInvalidArgumentException $e) {
239 14
                return Kernel::create(Url::class, [$url]);
240
            }
241
        }
242
243
        throw new InvalidArgumentException(
244
            sprintf('Invalid relation URL "%s"', $url),
245
            InvalidArgumentException::INVALID_RELATION_URL
246
        );
247
    }
248
}
249