Completed
Pull Request — master (#1381)
by Damian
02:47
created

SiteTreeLinkTracking::trackLinksInField()   F

Complexity

Conditions 25
Paths 1512

Size

Total Lines 100
Code Lines 59

Duplication

Lines 20
Ratio 20 %
Metric Value
dl 20
loc 100
rs 2
cc 25
eloc 59
nc 1512
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @package cms
5
 * @subpackage model
6
 */
7
8
/**
9
 * Adds tracking of links in any HTMLText fields which reference SiteTree or File items.
10
 *
11
 * Attaching this to any DataObject will add four fields which contain all links to SiteTree and File items
12
 * referenced in any HTMLText fields, and two booleans to indicate if there are any broken links. Call
13
 * augmentSyncLinkTracking to update those fields with any changes to those fields.
14
 *
15
 * Note that since both SiteTree and File are versioned, LinkTracking and ImageTracking will
16
 * only be enabled for the Stage record.
17
 *
18
 * {@see SiteTreeFileExtension} for the extension applied to {@see File}
19
 *
20
 * @property SiteTree $owner
21
 *
22
 * @property bool $HasBrokenFile
23
 * @property bool $HasBrokenLink
24
 *
25
 * @method ManyManyList LinkTracking() List of site pages linked on this page.
26
 * @method ManyManyList ImageTracking() List of Images linked on this page.
27
 * @method ManyManyList BackLinkTracking List of site pages that link to this page.
28
 */
29
class SiteTreeLinkTracking extends DataExtension {
30
31
	public $parser;
32
33
	private static $dependencies = array(
34
		'parser' => '%$SiteTreeLinkTracking_Parser'
35
	);
36
37
	private static $db = array(
38
		"HasBrokenFile" => "Boolean",
39
		"HasBrokenLink" => "Boolean"
40
	);
41
42
	private static $many_many = array(
43
		"LinkTracking" => "SiteTree",
44
		"ImageTracking" => "File"
45
	);
46
47
	private static $belongs_many_many = array(
48
		"BackLinkTracking" => "SiteTree.LinkTracking"
49
	);
50
51
	private static $many_many_extraFields = array(
52
		"LinkTracking" => array("FieldName" => "Varchar"),
53
		"ImageTracking" => array("FieldName" => "Varchar")
54
	);
55
56
	/**
57
	 * Scrape the content of a field to detect anly links to local SiteTree pages or files
58
	 *
59
	 * @todo - Replace image tracking with shortcodes
60
	 *
61
	 * @param string $fieldName The name of the field on {@link @owner} to scrape
62
	 */
63
	public function trackLinksInField($fieldName) {
64
		$record = $this->owner;
65
66
		$linkedPages = array();
67
		$linkedFiles = array();
68
69
		$htmlValue = Injector::inst()->create('HTMLValue', $record->$fieldName);
70
		$links = $this->parser->process($htmlValue);
71
72
		// Highlight broken links in the content.
73
		foreach ($links as $link) {
74
			$classStr = trim($link['DOMReference']->getAttribute('class'));
75
			if (!$classStr) {
76
				$classes = array();
77
			} else {
78
				$classes = explode(' ', $classStr);
79
			}
80
81
			// Add or remove the broken class from the link, depending on the link status.
82
			if ($link['Broken']) {
83
				$classes = array_unique(array_merge($classes, array('ss-broken')));
84
			} else {
85
				$classes = array_diff($classes, array('ss-broken'));
86
			}
87
88
			if (!empty($classes)) {
89
				$link['DOMReference']->setAttribute('class', implode(' ', $classes));
90
			} else {
91
				$link['DOMReference']->removeAttribute('class');
92
			}
93
		}
94
		$record->$fieldName = $htmlValue->getContent();
95
96
		// Populate link tracking for internal links & links to asset files.
97
		foreach ($links as $link) {
98
			switch ($link['Type']) {
99
				case 'sitetree':
100
					if ($link['Broken']) {
101
						$record->HasBrokenLink = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
102
					} else {
103
						$linkedPages[] = $link['Target'];
104
					}
105
					break;
106
107
				case 'file':
108
					if ($link['Broken']) {
109
						$record->HasBrokenFile = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
110
					} else {
111
						$linkedFiles[] = $link['Target'];
112
					}
113
					break;
114
115
				default:
116
					if ($link['Broken']) {
117
						$record->HasBrokenLink = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
118
					}
119
					break;
120
			}
121
		}
122
123
		// Add file tracking for image references
124
		if($images = $htmlValue->getElementsByTagName('img')) foreach($images as $img) {
125
			// {@see HtmlEditorField} for data-fileid source
126
			$fileID = $img->getAttribute('data-fileid');
127
			if(!$fileID) {
128
				continue;
129
			}
130
131
			// Assuming a local file is linked, check if it's valid
132
			if($image = File::get()->byID($fileID)) {
133
				$linkedFiles[] = $image->ID;
134
			} else {
135
				$record->HasBrokenFile = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
136
			}
137
		}
138
139
		// Update the "LinkTracking" many_many
140 View Code Duplication
		if($record->ID && $record->manyManyComponent('LinkTracking') && ($tracker = $record->LinkTracking())) {
0 ignored issues
show
Bug introduced by
The method LinkTracking() does not exist on SiteTree. Did you maybe mean syncLinkTracking()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
141
			$tracker->removeByFilter(array(
142
				sprintf('"FieldName" = ? AND "%s" = ?', $tracker->getForeignKey())
143
					=> array($fieldName, $record->ID)
144
			));
145
146
			if($linkedPages) foreach($linkedPages as $item) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $linkedPages of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
147
				$tracker->add($item, array('FieldName' => $fieldName));
148
			}
149
		}
150
151
		// Update the "ImageTracking" many_many
152 View Code Duplication
		if($record->ID && $record->manyManyComponent('ImageTracking') && ($tracker = $record->ImageTracking())) {
0 ignored issues
show
Documentation Bug introduced by
The method ImageTracking does not exist on object<SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
153
			$tracker->removeByFilter(array(
154
				sprintf('"FieldName" = ? AND "%s" = ?', $tracker->getForeignKey())
155
					=> array($fieldName, $record->ID)
156
			));
157
158
			if($linkedFiles) foreach($linkedFiles as $item) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $linkedFiles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
159
				$tracker->add($item, array('FieldName' => $fieldName));
160
			}
161
		}
162
	}
163
164
	/**
165
	 * Find HTMLText fields on {@link owner} to scrape for links that need tracking
166
	 *
167
	 * @todo Support versioned many_many for per-stage page link tracking
168
	 */
169
	public function augmentSyncLinkTracking() {
170
		// Skip live tracking
171
		if(\Versioned::current_stage() == \Versioned::get_live_stage()) {
172
			return;
173
		}
174
175
		// Reset boolean broken flags
176
		$this->owner->HasBrokenLink = false;
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
177
		$this->owner->HasBrokenFile = false;
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
178
179
		// Build a list of HTMLText fields
180
		$allFields = $this->owner->db();
181
		$htmlFields = array();
182
		foreach($allFields as $field => $fieldSpec) {
0 ignored issues
show
Bug introduced by
The expression $allFields of type array|string|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
183
			if(preg_match('/([^(]+)/', $fieldSpec, $matches)) {
184
				$class = $matches[0];
185
				if(class_exists($class)){
186
					if($class == 'HTMLText' || is_subclass_of($class, 'HTMLText')) $htmlFields[] = $field;
187
				}
188
			}
189
		}
190
191
		foreach($htmlFields as $field) {
192
			$this->trackLinksInField($field);
193
		}
194
	}
195
}
196
197
/**
198
 * A helper object for extracting information about links.
199
 */
200
class SiteTreeLinkTracking_Parser {
201
202
	/**
203
	 * Finds the links that are of interest for the link tracking automation. Checks for brokenness and attaches
204
	 * extracted metadata so consumers can decide what to do with the DOM element (provided as DOMReference).
205
	 *
206
	 * @param SS_HTMLValue $htmlValue Object to parse the links from.
207
	 * @return array Associative array containing found links with the following field layout:
208
	 *		Type: string, name of the link type
209
	 *		Target: any, a reference to the target object, depends on the Type
210
	 *		Anchor: string, anchor part of the link
211
	 *		DOMReference: DOMElement, reference to the link to apply changes.
212
	 *		Broken: boolean, a flag highlighting whether the link should be treated as broken.
213
	 */
214
	public function process(SS_HTMLValue $htmlValue) {
215
		$results = array();
216
217
		$links = $htmlValue->getElementsByTagName('a');
218
		if(!$links) return $results;
219
220
		foreach($links as $link) {
221
			if (!$link->hasAttribute('href')) continue;
222
223
			$href = Director::makeRelative($link->getAttribute('href'));
224
225
			// Definitely broken links.
226
			if($href == '' || $href[0] == '/') {
227
				$results[] = array(
228
					'Type' => 'broken',
229
					'Target' => null,
230
					'Anchor' => null,
231
					'DOMReference' => $link,
232
					'Broken' => true
233
				);
234
235
				continue;
236
			}
237
238
			// Link to a page on this site.
239
			$matches = array();
240
			if(preg_match('/\[sitetree_link(?:\s*|%20|,)?id=([0-9]+)\](#(.*))?/i', $href, $matches)) {
241
				$page = DataObject::get_by_id('SiteTree', $matches[1]);
242
				$broken = false;
243
244
				if (!$page) {
245
					// Page doesn't exist.
246
					$broken = true;
247
				} else if (!empty($matches[3])) {
248
					$anchor = preg_quote($matches[3], '/');
249
250
					if (!preg_match("/(name|id)=\"{$anchor}\"/", $page->Content)) {
251
						// Broken anchor on the target page.
252
						$broken = true;
253
					}
254
				}
255
256
				$results[] = array(
257
					'Type' => 'sitetree',
258
					'Target' => $matches[1],
259
					'Anchor' => empty($matches[3]) ? null : $matches[3],
260
					'DOMReference' => $link,
261
					'Broken' => $broken
262
				);
263
264
				continue;
265
			}
266
267
			// Link to a file on this site.
268
			$matches = array();
269 View Code Duplication
			if(preg_match('/\[file_link(?:\s*|%20|,)?id=([0-9]+)\]/i', $href, $matches)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
270
				$results[] = array(
271
					'Type' => 'file',
272
					'Target' => $matches[1],
273
					'Anchor' => null,
274
					'DOMReference' => $link,
275
					'Broken' => !DataObject::get_by_id('File', $matches[1])
276
				);
277
278
				continue;
279
			}
280
281
			// Local anchor.
282
			$matches = array();
283 View Code Duplication
			if(preg_match('/^#(.*)/i', $href, $matches)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
284
				$results[] = array(
285
					'Type' => 'localanchor',
286
					'Target' => null,
287
					'Anchor' => $matches[1],
288
					'DOMReference' => $link,
289
					'Broken' => !preg_match("#(name|id)=\"{$matches[1]}\"#", $htmlValue->getContent())
290
				);
291
292
				continue;
293
			}
294
295
		}
296
297
		return $results;
298
	}
299
300
}
301