DocumentCleaner   A
last analyzed

Complexity

Total Complexity 41

Size/Duplication

Total Lines 317
Duplicated Lines 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 41
eloc 138
c 3
b 1
f 0
dl 0
loc 317
rs 9.1199

9 Methods

Rating   Name   Duplication   Size   Complexity  
A removeXPath() 0 10 4
A remove() 0 10 4
A replace() 0 10 4
A run() 0 27 2
A convertToParagraph() 0 17 3
A getFlushedBuffer() 0 5 1
A removeBadTags() 0 33 5
A replaceElementsWithPara() 0 19 3
C getReplacementNodes() 0 68 15

How to fix   Complexity   

Complex Class

Complex classes like DocumentCleaner often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DocumentCleaner, and based on these observations, apply Extract Interface, too.

1
<?php declare(strict_types=1);
2
3
namespace Goose\Modules\Cleaners;
4
5
use Goose\Article;
6
use Goose\Traits\DocumentMutatorTrait;
7
use Goose\Modules\{AbstractModule, ModuleInterface};
8
use DOMWrap\{Text, Element, NodeList};
9
10
/**
11
 * Document Cleaner
12
 *
13
 * @package Goose\Modules\Cleaners
14
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
15
 */
16
class DocumentCleaner extends AbstractModule implements ModuleInterface {
17
    use DocumentMutatorTrait;
18
19
    /** @var array Element id/class/name to be removed that start with */
20
    private $startsWithNodes = [
21
        'adspot', 'conditionalAd-', 'hidden-', 'social-', 'publication', 'share-',
22
        'hp-', 'ad-', 'recommended-'
23
    ];
24
25
    /** @var array Element id/class/name to be removed that equal */
26
    private $equalsNodes = [
27
        'side', 'links', 'inset', 'print', 'fn', 'ad',
28
    ];
29
30
    /** @var array Element id/class/name to be removed that end with */
31
    private $endsWithNodes = [
32
        'meta'
33
    ];
34
35
    /** @var array Element id/class/name to be removed that contain */
36
    private $searchNodes = [
37
        'combx', 'retweet', 'mediaarticlerelated', 'menucontainer', 'navbar',
38
        'storytopbar-bucket', 'utility-bar', 'inline-share-tools', 'comment', // not commented
39
        'PopularQuestions', 'contact', 'foot', 'footer', 'Footer', 'footnote',
40
        'cnn_strycaptiontxt', 'cnn_html_slideshow', 'cnn_strylftcntnt',
41
        'shoutbox', 'sponsor', 'tags', 'socialnetworking', 'socialNetworking', 'scroll', // not scrollable
42
        'cnnStryHghLght', 'cnn_stryspcvbx', 'pagetools', 'post-attributes',
43
        'welcome_form', 'contentTools2', 'the_answers', 'communitypromo', 'promo_holder',
44
        'runaroundLeft', 'subscribe', 'vcard', 'articleheadings', 'date',
45
        'popup', 'author-dropdown', 'tools', 'socialtools', 'byline',
46
        'konafilter', 'KonaFilter', 'breadcrumbs', 'wp-caption-text', 'source',
47
        'legende', 'ajoutVideo', 'timestamp', 'js_replies', 'creative_commons', 'topics',
48
        'pagination', 'mtl', 'author', 'credit', 'toc_container', 'sharedaddy',
49
    ];
50
51
    /** @var array Element tagNames exempt from removal */
52
    private $exceptionSelectors = [
53
        'html', 'body',
54
    ];
55
56
    /**
57
     * Clean the contents of the supplied article document
58
     *
59
     * @inheritdoc
60
     */
61
    public function run(Article $article): self {
62
        $this->document($article->getDoc());
63
64
        $this->removeXPath('//comment()');
65
        $this->replace('em, strong, b, i, strike, del, ins', function($node) {
66
            return !$node->find('img')->count();
67
        });
68
        $this->replace('span[class~=dropcap], span[class~=drop_cap]');
69
        $this->remove('script, style');
70
        $this->remove('header, footer, input, form, button, aside');
71
        $this->removeBadTags();
72
        $this->remove("[id='caption'],[class='caption']");
73
        $this->remove("[id*=' google '],[class*=' google ']");
74
        $this->remove("[id*='more']:not([id^=entry-]),[class*='more']:not([class^=entry-])");
75
        $this->remove("[id*='facebook']:not([id*='-facebook']),[class*='facebook']:not([class*='-facebook'])");
76
        $this->remove("[id*='facebook-broadcasting'],[class*='facebook-broadcasting']");
77
        $this->remove("[id*='twitter']:not([id*='-twitter']),[class*='twitter']:not([class*='-twitter'])");
78
        $this->replace('span', function($node) {
79
            if (is_null($node->parent())) {
80
                return false;
81
            }
82
83
            return $node->parent()->is('p');
84
        });
85
        $this->convertToParagraph('div, span, article');
86
87
        return $this;
88
    }
89
90
    /**
91
     * Remove via CSS selectors
92
     *
93
     * @param string $selector
94
     * @param callable $callback
95
     *
96
     * @return self
97
     */
98
    private function remove(string $selector, callable $callback = null): self {
99
        $nodes = $this->document()->find($selector);
100
101
        foreach ($nodes as $node) {
102
            if (is_null($callback) || $callback($node)) {
103
                $node->destroy();
104
            }
105
        }
106
107
        return $this;
108
    }
109
110
    /**
111
     * Remove using via XPath expressions
112
     *
113
     * @param string $expression
114
     * @param callable $callback
115
     *
116
     * @return self
117
     */
118
    private function removeXPath(string $expression, callable $callback = null): self {
119
        $nodes = $this->document()->findXPath($expression);
120
121
        foreach ($nodes as $node) {
122
            if (is_null($callback) || $callback($node)) {
123
                $node->destroy();
124
            }
125
        }
126
127
        return $this;
128
    }
129
130
    /**
131
     * Replace node with its textual contents via CSS selectors
132
     *
133
     * @param string $selector
134
     * @param callable $callback
135
     *
136
     * @return self
137
     */
138
    private function replace(string $selector, callable $callback = null): self {
139
        $nodes = $this->document()->find($selector);
140
141
        foreach ($nodes as $node) {
142
            if (is_null($callback) || $callback($node)) {
143
                $node->substituteWith(new Text((string)$node->text()));
144
            }
145
        }
146
147
        return $this;
148
    }
149
150
    /**
151
     * Remove unwanted junk elements based on pre-defined CSS selectors
152
     *
153
     * @return self
154
     */
155
    private function removeBadTags(): self {
156
        $lists = [
157
            "[%s^='%s']" => $this->startsWithNodes,
158
            "[%s*='%s']" => $this->searchNodes,
159
            "[%s$='%s']" => $this->endsWithNodes,
160
            "[%s='%s']" => $this->equalsNodes,
161
        ];
162
163
        $attrs = [
164
            'id',
165
            'class',
166
            'name',
167
        ];
168
169
        $exceptions = array_map(function($value) {
170
            return ':not(' . $value . ')';
171
        }, $this->exceptionSelectors);
172
173
        $exceptions = implode('', $exceptions);
174
175
        foreach ($lists as $expr => $list) {
176
            foreach ($list as $value) {
177
                foreach ($attrs as $attr) {
178
                    $selector = sprintf($expr, $attr, $value) . $exceptions;
179
180
                    foreach ($this->document()->find($selector) as $node) {
181
                        $node->destroy();
182
                    }
183
                }
184
            }
185
        }
186
187
        return $this;
188
    }
189
190
    /**
191
     * Replace supplied element with <p> new element.
192
     *
193
     * @param Element $node
194
     *
195
     * @return self|null
196
     */
197
    private function replaceElementsWithPara(Element $node): ?self {
198
        // Check to see if the node no longer exist.
199
        // 'Ghost' nodes have their ownerDocument property set to null - will throw a warning on access.
200
        // Use another common property with isset() - won't throw any warnings.
201
        if (!isset($node->nodeName)) {
202
            return null;
203
        }
204
205
        $newEl = $this->document()->createElement('p');
206
207
        $newEl->appendWith($node->contents()->detach());
0 ignored issues
show
Bug introduced by
The method appendWith() does not exist on DOMElement. Did you maybe mean append()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

207
        $newEl->/** @scrutinizer ignore-call */ 
208
                appendWith($node->contents()->detach());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
208
209
        foreach ($node->attributes as $attr) {
210
            $newEl->attr($attr->localName, $attr->nodeValue);
0 ignored issues
show
introduced by
The method attr() does not exist on DOMElement. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

210
            $newEl->/** @scrutinizer ignore-call */ 
211
                    attr($attr->localName, $attr->nodeValue);
Loading history...
211
        }
212
213
        $node->substituteWith($newEl);
214
215
        return $this;
216
    }
217
218
    /**
219
     * Convert wanted elements to <p> elements.
220
     *
221
     * @param string $selector
222
     *
223
     * @return self
224
     */
225
    private function convertToParagraph(string $selector): self {
226
        $nodes = $this->document()->find($selector);
227
228
        foreach ($nodes as $node) {
229
            $tagNodes = $node->find('a, blockquote, dl, div, img, ol, p, pre, table, ul');
230
231
            if (!$tagNodes->count()) {
232
                $this->replaceElementsWithPara($node);
233
            } else {
234
                $replacements = $this->getReplacementNodes($node);
235
236
                $node->contents()->destroy();
237
                $node->appendWith($replacements);
238
            }
239
        }
240
241
        return $this;
242
    }
243
244
    /**
245
     * Generate new <p> element with supplied content.
246
     *
247
     * @param NodeList $replacementNodes
248
     *
249
     * @return Element
250
     */
251
    private function getFlushedBuffer(NodeList $replacementNodes): Element {
252
        $newEl = $this->document()->createElement('p');
253
        $newEl->appendWith($replacementNodes);
254
255
        return $newEl;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $newEl returns the type DOMElement which includes types incompatible with the type-hinted return DOMWrap\Element.
Loading history...
256
    }
257
258
    /**
259
     * Generate <p> element replacements for supplied elements child nodes as required.
260
     *
261
     * @param Element $node
262
     *
263
     * @return NodeList $nodesToReturn Replacement elements
264
     */
265
    private function getReplacementNodes(Element $node): NodeList {
266
        $nodesToReturn = $node->newNodeList();
267
        $nodesToRemove = $node->newNodeList();
268
        $replacementNodes = $node->newNodeList();
269
270
        $fnCompareSiblingNodes = function($node) {
271
            if ($node->is(':not(a)') || $node->nodeType == XML_TEXT_NODE) {
272
                return true;
273
            }
274
        };
275
276
        foreach ($node->contents() as $child) {
277
            if ($child->is('p') && $replacementNodes->count()) {
278
                $nodesToReturn[] = $this->getFlushedBuffer($replacementNodes);
279
                $replacementNodes->fromArray([]);
280
                $nodesToReturn[] = $child;
281
            } else if ($child->nodeType == XML_TEXT_NODE) {
282
                $replaceText = $child->text();
283
284
                if (!empty($replaceText)) {
285
                    // Get all previous sibling <a> nodes, the current text node, and all next sibling <a> nodes.
286
                    $siblings = $child
287
                        ->precedingUntil($fnCompareSiblingNodes, 'a')
288
                        ->merge([$child])
289
                        ->merge($child->followingUntil($fnCompareSiblingNodes, 'a'));
290
291
                    foreach ($siblings as $sibling) {
292
                        // Place current nodes textual contents in-between previous and next nodes.
293
                        if ($sibling->isSameNode($child)) {
294
                            $replacementNodes[] = new Text($replaceText);
295
296
                        // Grab the contents of any unprocessed <a> siblings and flag them for removal.
297
                        } else if ($sibling->getAttribute('grv-usedalready') != 'yes') {
298
                            $sibling->setAttribute('grv-usedalready', 'yes');
299
300
                            $replacementNodes[] = $sibling->cloneNode(true);
301
                            $nodesToRemove[] = $sibling;
302
                        }
303
304
                    }
305
                }
306
307
                $nodesToRemove[] = $child;
308
            } else {
309
                if ($replacementNodes->count()) {
310
                    $nodesToReturn[] = $this->getFlushedBuffer($replacementNodes);
311
                    $replacementNodes->fromArray([]);
312
                }
313
314
                $nodesToReturn[] = $child;
315
            }
316
        }
317
318
        // Flush any remaining replacementNodes left over from text nodes.
319
        if ($replacementNodes->count()) {
320
            $nodesToReturn[] = $this->getFlushedBuffer($replacementNodes);
321
        }
322
323
        // Remove potential duplicate <a> tags.
324
        foreach ($nodesToReturn as $key => $return) {
325
            if ($nodesToRemove->exists($return)) {
326
                unset($nodesToReturn[$key]);
327
            }
328
        }
329
330
        $nodesToRemove->destroy();
331
332
        return $nodesToReturn;
333
    }
334
}
335