Completed
Push — new-committers ( 29cb6f...bcba16 )
by Sam
12:18 queued 33s
created

Text::requireField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 12

Duplication

Lines 18
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 18
loc 18
rs 9.4285
cc 1
eloc 12
nc 1
nop 0
1
<?php
2
/**
3
 * Represents a variable-length string of up to 2 megabytes, designed to store raw text
4
 *
5
 * Example definition via {@link DataObject::$db}:
6
 * <code>
7
 * static $db = array(
8
 * 	"MyDescription" => "Text",
9
 * );
10
 * </code>
11
 *
12
 * @see HTMLText
13
 * @see HTMLVarchar
14
 * @see Varchar
15
 *
16
 * @package framework
17
 * @subpackage model
18
 */
19
class Text extends StringField {
20
21
	private static $casting = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
22
		"AbsoluteLinks" => "Text",
23
		"BigSummary" => "Text",
24
		"ContextSummary" => "Text",
25
		"FirstParagraph" => "Text",
26
		"FirstSentence" => "Text",
27
		"LimitCharacters" => "Text",
28
		"LimitSentences" => "Text",
29
		"Summary" => "Text",
30
		'EscapeXML' => 'Text',
31
		'LimitWordCount' => 'Text',
32
		'LimitWordCountXML' => 'HTMLText',
33
	);
34
35
	/**
36
 	 * (non-PHPdoc)
37
 	 * @see DBField::requireField()
38
 	 */
39 View Code Duplication
	public function requireField() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
40
		$charset = Config::inst()->get('MySQLDatabase', 'charset');
41
		$collation = Config::inst()->get('MySQLDatabase', 'collation');
42
43
		$parts = array(
44
			'datatype' => 'mediumtext',
45
			'character set' => $charset,
46
			'collate' => $collation,
47
			'arrayValue' => $this->arrayValue
48
		);
49
50
		$values= array(
51
			'type' => 'text',
52
			'parts' => $parts
53
		);
54
55
		DB::require_field($this->tableName, $this->name, $values, $this->default);
0 ignored issues
show
Bug introduced by
The property default does not seem to exist. Did you mean default_search_filter_class?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Unused Code introduced by
The call to DB::require_field() has too many arguments starting with $this->default.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Documentation introduced by
$values is of type array<string,string|arra...arrayValue\":\"?\"}>"}>, but the function expects a string.

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...
56
	}
57
58
	/**
59
	 * Return the value of the field with relative links converted to absolute urls.
60
	 * @return string
61
	 */
62
	public function AbsoluteLinks() {
63
		return HTTP::absoluteURLs($this->value);
64
	}
65
66
	/**
67
	 * Limit sentences, can be controlled by passing an integer.
68
	 *
69
	 * @param int $sentCount The amount of sentences you want.
70
	 */
71
	public function LimitSentences($sentCount = 2) {
72
		if(!is_numeric($sentCount)) {
73
			user_error("Text::LimitSentence() expects one numeric argument", E_USER_NOTICE);
74
		}
75
76
		$output = array();
77
		$data = trim(Convert::xml2raw($this->value));
78
		$sentences = explode('.', $data);
79
80
		if ($sentCount == 0) return '';
81
82
		for($i = 0; $i < $sentCount; $i++) {
83
			if(isset($sentences[$i])) {
84
				$sentence = trim($sentences[$i]);
85
				if(!empty($sentence)) $output[] .= $sentence;
86
			}
87
		}
88
89
		return count($output)==0 ? '' : implode($output, '. ') . '.';
90
	}
91
92
93
	/**
94
	 * Caution: Not XML/HTML-safe - does not respect closing tags.
95
	 */
96
	public function FirstSentence() {
97
		$paragraph = Convert::xml2raw( $this->value );
98
		if( !$paragraph ) return "";
99
100
		$words = preg_split('/\s+/', $paragraph);
101 View Code Duplication
		foreach ($words as $i => $word) {
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...
102
			if (preg_match('/(!|\?|\.)$/', $word) && !preg_match('/(Dr|Mr|Mrs|Ms|Miss|Sr|Jr|No)\.$/i', $word)) {
103
				return implode(' ', array_slice($words, 0, $i+1));
104
			}
105
		}
106
107
		/* If we didn't find a sentence ending, use the summary. We re-call rather than using paragraph so that
108
		 * Summary will limit the result this time */
109
		return $this->Summary(20);
110
	}
111
112
	/**
113
	 * Caution: Not XML/HTML-safe - does not respect closing tags.
114
	 */
115
	public function Summary($maxWords = 50) {
116
		// get first sentence?
117
		// this needs to be more robust
118
		$value = Convert::xml2raw( $this->value /*, true*/ );
119
		if(!$value) return '';
120
121
		// grab the first paragraph, or, failing that, the whole content
122
		if(strpos($value, "\n\n")) $value = substr($value, 0, strpos($value, "\n\n"));
123
		$sentences = explode('.', $value);
124
		$count = count(explode(' ', $sentences[0]));
125
126
		// if the first sentence is too long, show only the first $maxWords words
127 View Code Duplication
		if($count > $maxWords) {
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...
128
			return implode( ' ', array_slice(explode( ' ', $sentences[0] ), 0, $maxWords)) . '...';
129
		}
130
131
		// add each sentence while there are enough words to do so
132
		$result = '';
133 View Code Duplication
		do {
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...
134
			$result .= trim(array_shift( $sentences )).'.';
135
			if(count($sentences) > 0) {
136
				$count += count(explode(' ', $sentences[0]));
137
			}
138
139
			// Ensure that we don't trim half way through a tag or a link
140
			$brokenLink = (
141
				substr_count($result,'<') != substr_count($result,'>')) ||
142
				(substr_count($result,'<a') != substr_count($result,'</a')
143
			);
144
		} while(($count < $maxWords || $brokenLink) && $sentences && trim( $sentences[0]));
0 ignored issues
show
Bug Best Practice introduced by
The expression $sentences 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...
145
146
		if(preg_match('/<a[^>]*>/', $result) && !preg_match( '/<\/a>/', $result)) $result .= '</a>';
147
148
		return Convert::raw2xml($result);
149
	}
150
151
	/**
152
	* Performs the same function as the big summary, but doesn't trim new paragraphs off data.
153
	* Caution: Not XML/HTML-safe - does not respect closing tags.
154
	*/
155
	public function BigSummary($maxWords = 50, $plain = true) {
156
		$result = '';
157
158
		// get first sentence?
159
		// this needs to be more robust
160
		$data = $plain ? Convert::xml2raw($this->value, true) : $this->value;
0 ignored issues
show
Unused Code introduced by
The call to Convert::xml2raw() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
161
162
		if(!$data) return '';
163
164
		$sentences = explode('.', $data);
165
		$count = count(explode(' ', $sentences[0]));
166
167
		// if the first sentence is too long, show only the first $maxWords words
168 View Code Duplication
		if($count > $maxWords) {
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...
169
			return implode(' ', array_slice(explode( ' ', $sentences[0] ), 0, $maxWords)) . '...';
170
		}
171
172
		// add each sentence while there are enough words to do so
173 View Code Duplication
		do {
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...
174
			$result .= trim(array_shift($sentences));
175
			if($sentences) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sentences 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...
176
				$result .= '. ';
177
				$count += count(explode(' ', $sentences[0]));
178
			}
179
180
			// Ensure that we don't trim half way through a tag or a link
181
			$brokenLink = (
182
				substr_count($result,'<') != substr_count($result,'>')) ||
183
				(substr_count($result,'<a') != substr_count($result,'</a')
184
			);
185
		} while(($count < $maxWords || $brokenLink) && $sentences && trim($sentences[0]));
0 ignored issues
show
Bug Best Practice introduced by
The expression $sentences 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...
186
187
		if(preg_match( '/<a[^>]*>/', $result) && !preg_match( '/<\/a>/', $result)) {
188
			$result .= '</a>';
189
		}
190
191
		return $result;
192
	}
193
194
	/**
195
	 * Caution: Not XML/HTML-safe - does not respect closing tags.
196
	 */
197
	public function FirstParagraph($plain = 1) {
198
		// get first sentence?
199
		// this needs to be more robust
200
		if($plain && $plain != 'html') {
201
			$data = Convert::xml2raw($this->value, true);
0 ignored issues
show
Unused Code introduced by
The call to Convert::xml2raw() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
202
			if(!$data) return "";
203
204
			// grab the first paragraph, or, failing that, the whole content
205
			$pos = strpos($data, "\n\n");
206
			if($pos) $data = substr($data, 0, $pos);
207
208
			return $data;
209
		} else {
210
			if(strpos($this->value, "</p>") === false) return $this->value;
211
212
			$data = substr($this->value, 0, strpos($this->value, "</p>") + 4);
213
214
			if(strlen($data) < 20 && strpos($this->value, "</p>", strlen($data))) {
215
				$data = substr($this->value, 0, strpos( $this->value, "</p>", strlen($data)) + 4 );
216
			}
217
218
			return $data;
219
		}
220
	}
221
222
	/**
223
	 * Perform context searching to give some context to searches, optionally
224
	 * highlighting the search term.
225
	 *
226
	 * @param int $characters Number of characters in the summary
227
	 * @param boolean $string Supplied string ("keywords")
228
	 * @param boolean $striphtml Strip HTML?
229
	 * @param boolean $highlight Add a highlight <span> element around search query?
230
	 * @param String prefix text
231
	 * @param String suffix
232
	 *
233
	 * @return string
234
	 */
235
	public function ContextSummary($characters = 500, $string = false, $striphtml = true, $highlight = true,
236
			$prefix = "... ", $suffix = "...") {
237
238
		if(!$string) {
239
			// Use the default "Search" request variable (from SearchForm)
240
			$string = isset($_REQUEST['Search']) ? $_REQUEST['Search'] : '';
241
		}
242
243
		// Remove HTML tags so we don't have to deal with matching tags
244
		$text = $striphtml ? $this->NoHTML() : $this->value;
245
246
		// Find the search string
247
		$position = (int) stripos($text, $string);
248
249
		// We want to search string to be in the middle of our block to give it some context
250
		$position = max(0, $position - ($characters / 2));
251
252
		if($position > 0) {
253
			// We don't want to start mid-word
254
			$position = max((int) strrpos(substr($text, 0, $position), ' '),
255
				(int) strrpos(substr($text, 0, $position), "\n"));
256
		}
257
258
		$summary = substr($text, $position, $characters);
259
		$stringPieces = explode(' ', $string);
260
261
		if($highlight) {
262
			// Add a span around all key words from the search term as well
263
			if($stringPieces) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $stringPieces 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...
264
265
				foreach($stringPieces as $stringPiece) {
266
					if(strlen($stringPiece) > 2) {
267
						$summary = str_ireplace($stringPiece, "<span class=\"highlight\">$stringPiece</span>",
268
							$summary);
269
					}
270
				}
271
			}
272
		}
273
		$summary = trim($summary);
274
275
		if($position > 0) $summary = $prefix . $summary;
276
		if(strlen($this->value) > ($characters + $position)) $summary = $summary . $suffix;
277
278
		return $summary;
279
	}
280
281
	/**
282
	 * Allows a sub-class of TextParser to be rendered.
283
	 *
284
	 * @see TextParser for implementation details.
285
	 * @return string
286
	 */
287
	public function Parse($parser = "TextParser") {
288
		if($parser == "TextParser" || is_subclass_of($parser, "TextParser")) {
289
			$obj = new $parser($this->value);
290
			return $obj->parse();
291
		} else {
292
			// Fallback to using raw2xml and show a warning
293
			// TODO Don't kill script execution, we can continue without losing complete control of the app
294
			user_error("Couldn't find an appropriate TextParser sub-class to create (Looked for '$parser')."
295
				. "Make sure it sub-classes TextParser and that you've done ?flush=1.", E_USER_WARNING);
296
			return Convert::raw2xml($this->value);
0 ignored issues
show
Bug Compatibility introduced by
The expression \Convert::raw2xml($this->value); of type array|string adds the type array to the return on line 296 which is incompatible with the return type documented by Text::Parse of type string.
Loading history...
297
		}
298
	}
299
300
	/**
301
	 * (non-PHPdoc)
302
	 * @see DBField::scaffoldFormField()
303
	 */
304
	public function scaffoldFormField($title = null, $params = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
305
		if(!$this->nullifyEmpty) {
306
			// Allow the user to select if it's null instead of automatically assuming empty string is
307
			return new NullableField(new TextareaField($this->name, $title));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \NullableFiel...($this->name, $title)); (NullableField) is incompatible with the return type of the parent method DBField::scaffoldFormField of type TextField.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
308
		} else {
309
			// Automatically determine null (empty string)
310
			return new TextareaField($this->name, $title);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \TextareaField($this->name, $title); (TextareaField) is incompatible with the return type of the parent method DBField::scaffoldFormField of type TextField.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
311
		}
312
	}
313
314
	/**
315
	 * (non-PHPdoc)
316
	 * @see DBField::scaffoldSearchField()
317
	 */
318
	public function scaffoldSearchField($title = null, $params = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
319
		return new TextField($this->name, $title);
320
	}
321
}
322