Completed
Push — master ( ff0a6e...e40fc7 )
by Joschi
02:55
created

CommonMarkPayloadProcessor::addRefersToRelation()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 7
cc 3
eloc 4
nc 2
nop 2
ccs 6
cts 6
cp 1
crap 3
rs 9.4285
1
<?php
2
3
/**
4
 * apparat-object
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Object
8
 * @subpackage  Apparat\Object\Infrastructure
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\Infrastructure\Utilities;
38
39
use Apparat\Kernel\Ports\Kernel;
40
use Apparat\Object\Application\Contract\CommonMarkPayloadProcessorInterface;
41
use Apparat\Object\Application\Model\Object\AbstractCommonMarkObject;
42
use Apparat\Object\Ports\Relation;
43
use League\CommonMark\Block\Element\Document;
44
use League\CommonMark\DocParser;
45
use League\CommonMark\DocumentProcessorInterface;
46
use League\CommonMark\Environment;
47
use League\CommonMark\Inline\Element\Image;
48
use League\CommonMark\Inline\Element\Link;
49
50
/**
51
 * CommonMark payload processor
52
 *
53
 * @package Apparat\Object
54
 * @subpackage Apparat\Object\Infrastructure
55
 */
56
class CommonMarkPayloadProcessor extends AbstractPayloadProcessor
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces between "AbstractPayloadProcessor" and comma; 1 found
Loading history...
57
    implements CommonMarkPayloadProcessorInterface, DocumentProcessorInterface
0 ignored issues
show
Coding Style introduced by
The implements keyword must be on the same line as the class name
Loading history...
58
{
59
    /**
60
     * Mailto URL scheme
61
     *
62
     * @var string
63
     */
64
    const SCHEME_MAILTO = 'mailto';
65
    /**
66
     * List of refers-to relation URLs
67
     *
68
     * @var array
69
     */
70
    protected $refersTo;
71
    /**
72
     * List of embeds relation URLs
73
     *
74
     * @var array
75
     */
76
    protected $embeds;
77
    /**
78
     * Owning CommonMark object
79
     *
80
     * @var AbstractCommonMarkObject
81
     */
82
    protected $object;
83
84
    /**
85
     * Process the payload of an object
86
     *
87
     * @param string $payload Payload
88
     * @return string Processed payload
89
     */
90 4
    public function processPayload($payload)
91
    {
92
        // Reset all relevant relations
93 4
        $this->resetRefersToRelations();
94 4
        $this->resetEmbedsRelations();
95
96 4
        $env = Environment::createCommonMarkEnvironment();
97 4
        $env->addDocumentProcessor($this);
98
99
        // Parse and process the object payload
100
        /** @var DocParser $docParser */
101 4
        $docParser = Kernel::create(DocParser::class, [$env]);
102 4
        $docParser->parse($payload);
103
104 4
        return $payload;
105
    }
106
107
    /**
108
     * Reset the refers-to relations
109
     */
110 4
    protected function resetRefersToRelations()
111
    {
112 4
        $this->refersTo = [];
113
114
        // Run through all refers-to relations and delete them
115 4
        foreach ($this->object->findRelations([Relation::TYPE => Relation::REFERS_TO]) as $refersToRelation) {
116 1
            $this->object->deleteRelation($refersToRelation);
117 4
        }
118 4
    }
119
120
    /**
121
     * Reset the embeds relations
122
     */
123 4
    protected function resetEmbedsRelations()
124
    {
125 4
        $this->embeds = [];
126
127
        // Run through all refers-to relations and delete them
128 4
        foreach ($this->object->findRelations([Relation::TYPE => Relation::EMBEDS]) as $embedsRelation) {
129 1
            $this->object->deleteRelation($embedsRelation);
130 4
        }
131 4
    }
132
133
    /**
134
     * Process the CommonMark AST
135
     *
136
     * @param Document $document CommonMark AST
137
     * @return void
138
     */
139 4
    public function processDocument(Document $document)
140
    {
141 4
        $walker = $document->walker();
142 4
        while ($event = $walker->next()) {
143 4
            $node = $event->getNode();
144
145
            // Process link starts as refers-to relations
146 4
            if (($node instanceof Link) && $event->isEntering()) {
147 1
                $this->addRefersToRelation(
148 1
                    $this->stripFragment($node->getUrl()),
149 1
                    empty($node->data['title']) ? null : $node->data['title']
150 1
                );
151 1
            }
152
153
            // Process image starts as embeds relations
154 4
            if (($node instanceof Image) && $event->isEntering()) {
155 1
                $this->addEmbedsRelation(
156 1
                    $this->stripFragment($node->getUrl()),
157 1
                    empty($node->data['title']) ? null : $node->data['title']
158 1
                );
159 1
            }
160 4
        }
161 4
    }
162
163
    /**
164
     * Add a refers-to relation
165
     *
166
     * @param string $url Referred URL
167
     * @param string $label Label
168
     */
169 1
    protected function addRefersToRelation($url, $label = null)
170
    {
171 1
        if (strlen($url) && !array_key_exists($url, $this->refersTo)) {
172 1
            $this->refersTo[$url] = true;
173 1
            $this->object->addRelation($this->getRelationString($url, $label), Relation::REFERS_TO);
174 1
        }
175 1
    }
176
177
    /**
178
     * Create a relation string
179
     *
180
     * @param string $url URL
181
     * @param string $label Label
182
     * @return string relation string
183
     */
184 1
    protected function getRelationString($url, $label)
185
    {
186 1
        $relationString = (strtolower(parse_url($url, PHP_URL_SCHEME)) == self::SCHEME_MAILTO)
187 1
            ? '<'.substr($url, strlen(self::SCHEME_MAILTO) + 1).'>'
188 1
            : $url;
189 1
        if (!empty($label)) {
190 1
            $relationString .= ' '.$label;
191 1
        }
192 1
        return $relationString;
193
    }
194
195
    /**
196
     * Strip off the fragment of an URL
197
     *
198
     * @param string $url URL
199
     * @return string URL with fragmet stripped
200
     */
201 1
    protected function stripFragment($url)
202
    {
203 1
        $fragment = parse_url($url, PHP_URL_FRAGMENT);
204 1
        if (!empty($fragment) && (substr($url, -strlen($fragment) - 1) == '#'.$fragment)) {
205 1
            $url = substr($url, 0, -strlen($fragment) - 1);
206 1
        }
207 1
        return $url;
208
    }
209
210
    /**
211
     * Add an embeds relation
212
     *
213
     * @param string $url Embedded URL
214
     * @param string $label Label
215
     */
216 1
    protected function addEmbedsRelation($url, $label = null)
217
    {
218 1
        if (strlen($url) && !array_key_exists($url, $this->embeds)) {
219 1
            $this->embeds[$url] = true;
220 1
            $this->object->addRelation($this->getRelationString($url, $label), Relation::EMBEDS);
221 1
        }
222 1
    }
223
}
224