Completed
Push — master ( 2ca52b...7d8595 )
by Joschi
02:51
created

RelationFactory::parseRelationString()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 50
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6.6393

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 25
c 2
b 0
f 0
nc 8
nop 2
dl 0
loc 50
ccs 17
cts 23
cp 0.7391
crap 6.6393
rs 8.6315
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\ApparatUrl;
41
use Apparat\Object\Domain\Model\Path\Url;
42
use Apparat\Object\Domain\Model\Relation\ContributedByRelation;
43
use Apparat\Object\Domain\Model\Relation\ContributesRelation;
44
use Apparat\Object\Domain\Model\Relation\EmbeddedRelation;
45
use Apparat\Object\Domain\Model\Relation\EmbedsRelation;
46
use Apparat\Object\Domain\Model\Relation\InvalidArgumentException;
47
use Apparat\Object\Domain\Model\Relation\LikedByRelation;
48
use Apparat\Object\Domain\Model\Relation\LikesRelation;
49
use Apparat\Object\Domain\Model\Relation\OutOfBoundsException;
50
use Apparat\Object\Domain\Model\Relation\ReferredByRelation;
51
use Apparat\Object\Domain\Model\Relation\RefersToRelation;
52
use Apparat\Object\Domain\Model\Relation\RelationInterface;
53
use Apparat\Object\Domain\Model\Relation\RepliedByRelation;
54
use Apparat\Object\Domain\Model\Relation\RepliesToRelation;
55
use Apparat\Object\Domain\Model\Relation\RepostedByRelation;
56
use Apparat\Object\Domain\Model\Relation\RepostsRelation;
57
use Apparat\Object\Domain\Repository\RepositoryInterface;
58
use Apparat\Object\Infrastructure\Utilities\Validator;
59
60
/**
61
 * Relation factory
62
 *
63
 * @package Apparat\Object
64
 * @subpackage Apparat\Object\Domain
65
 */
66
class RelationFactory
67
{
68
    /**
69
     * URL component key
70
     *
71
     * @string
72
     */
73
    const PARSE_URL = 'url';
74
    /**
75
     * Label component key
76
     *
77
     * @string
78
     */
79
    const PARSE_LABEL = 'label';
80
    /**
81
     * Email component key
82
     *
83
     * @string
84
     */
85
    const PARSE_EMAIL = 'email';
86
    /**
87
     * Component relation coupling
88
     *
89
     * @string
90
     */
91
    const PARSE_COUPLING = 'coupling';
92
    /**
93
     * Relation types
94
     *
95
     * @var array
96
     */
97
    public static $relationTypes = [
98
        ContributesRelation::TYPE => ContributesRelation::class,
99
        ContributedByRelation::TYPE => ContributedByRelation::class,
100
        EmbedsRelation::TYPE => EmbedsRelation::class,
101
        EmbeddedRelation::TYPE => EmbeddedRelation::class,
102
        LikesRelation::TYPE => LikesRelation::class,
103
        LikedByRelation::TYPE => LikedByRelation::class,
104
        RefersToRelation::TYPE => RefersToRelation::class,
105
        ReferredByRelation::TYPE => ReferredByRelation::class,
106
        RepliesToRelation::TYPE => RepliesToRelation::class,
107
        RepliedByRelation::TYPE => RepliedByRelation::class,
108
        RepostsRelation::TYPE => RepostsRelation::class,
109
        RepostedByRelation::TYPE => RepostedByRelation::class,
110
    ];
111
112
    /**
113
     * Parse a relation serialization and instantiate the relation
114
     *
115
     * @param string $relationType Relation type
116
     * @param string $relation Relation serialization
117
     * @param RepositoryInterface $contextRepository Context repository
118
     * @return RelationInterface Relation object
119
     * @throws InvalidArgumentException If the relation format is invalid
120
     */
121 14
    public static function createFromString($relationType, $relation, RepositoryInterface $contextRepository)
122
    {
123
        // If the relation type is invalid
124 14
        if (empty($relationType) || empty(self::$relationTypes[$relationType])) {
125
            throw new OutOfBoundsException(
126
                sprintf('Invalid object relation type "%s"', $relationType),
127
                OutOfBoundsException::INVALID_OBJECT_RELATION_TYPE
128
            );
129
        }
130 14
        return Kernel::create(
131 14
            self::$relationTypes[$relationType],
132 14
            array_values(self::parseRelationString($relation, $contextRepository))
133
        );
134
    }
135
136
    /**
137
     * Parse a relation serialization and instantiate the relation object
138
     *
139
     * @param string $relation Relation serialization
140
     * @param RepositoryInterface $contextRepository Context repository
141
     * @return array Parsed relation components
142
     * @throws InvalidArgumentException If the email component has already been registered
143
     * @throws InvalidArgumentException If the URL component has already been registered
144
     */
145 14
    protected static function parseRelationString($relation, RepositoryInterface $contextRepository)
146
    {
147
        // TODO: Document exceptions
148
        $parsed = [
149 14
            self::PARSE_URL => null,
150 14
            self::PARSE_LABEL => null,
151 14
            self::PARSE_EMAIL => null,
152 14
            self::PARSE_COUPLING => RelationInterface::LOOSE_COUPLING,
153
        ];
154
155
        // Split the relation string and parse the components
156 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...
157
158
            // If it's an email component
159 14
            if (!strncmp('<', $relationComponent, 1)) {
160
                // If the email component has already been registered
161 14
                if (!empty($parsed[self::PARSE_EMAIL])) {
162
                    throw new InvalidArgumentException(
163
                        sprintf('Repeated relation email component "%s" not allowed', self::PARSE_EMAIL),
164
                        InvalidArgumentException::REPEATED_RELATION_COMPONENT_NOT_ALLOWED
165
                    );
166
                }
167
168 14
                $parsed[self::PARSE_EMAIL] = self::parseRelationEmail($relationComponent);
169 14
                continue;
170
            }
171
172
            // Next: Try to parse it as URL
173
            try {
174 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...
175
176
                // If the URL component has already been registered
177 14
                if (!empty($parsed[self::PARSE_URL])) {
178
                    throw new InvalidArgumentException(
179
                        sprintf('Repeated relation url component "%s" not allowed', self::PARSE_URL),
180
                        InvalidArgumentException::REPEATED_RELATION_COMPONENT_NOT_ALLOWED
181
                    );
182
                }
183
184 14
                $parsed[self::PARSE_URL] = $url;
185
186
                // Else: Process as label component
187 14
            } catch (\Exception $e) {
188 14
                echo $e->getMessage();
189 14
                $parsed[self::PARSE_LABEL] = trim($parsed[self::PARSE_LABEL].' '.$relationComponent);
190
            }
191
        }
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 14
    protected static function parseRelationEmail($relationEmail)
204
    {
205
        // If it's a valid email address
206 14
        if (preg_match('%^\<(.+)\>$%', $relationEmail, $emailAddress) && Validator::isEmail($emailAddress[1])) {
207 14
            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
     * @throws InvalidArgumentException If the relation URL is invalid
224
     */
225 14
    protected static function parseRelationUrl($url, &$coupling, RepositoryInterface $contextRepository)
226
    {
227 14
        if (strlen($url)) {
228
            // If the URL requires tight coupling
229 14
            if (!strncmp('!', $url, 1)) {
230 14
                $coupling = RelationInterface::TIGHT_COUPLING;
231 14
                $url = substr($url, 1);
232
            }
233
234
            // Try to instantiate as an apparat URL
235
            try {
236 14
                return Kernel::create(ApparatUrl::class, [$url, true, $contextRepository]);
237
238
                // If there's an apparat URL problem: Try to instantiate as a regular URL
239 14
            } catch (\Apparat\Object\Domain\Model\Path\InvalidArgumentException $e) {
240
                /** @var Url $urlInstance */
241 14
                $urlInstance = Kernel::create(Url::class, [$url]);
242 14
                if ($urlInstance->isAbsolute()) {
243 14
                    return $urlInstance;
244
                }
245
            }
246
        }
247
248 14
        throw new InvalidArgumentException(
249 14
            sprintf('Invalid relation URL "%s"', $url),
250 14
            InvalidArgumentException::INVALID_RELATION_URL
251
        );
252
    }
253
}
254