Completed
Push — master ( 4e5e31...e8f514 )
by Matt
02:38
created

trim::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 *
4
 * Topic Preview
5
 *
6
 * @copyright (c) 2014 Matt Friedman
7
 * @license GNU General Public License, version 2 (GPL-2.0)
8
 *
9
 */
10
11
namespace vse\topicpreview\core\trim;
12
13
class trim
14
{
15
	/** @var array An array of trim tools */
16
	protected $tools;
17
18
	/**
19
	 * Constructor
20
	 *
21
	 * @param manager $manager
22
	 * @access public
23
	 */
24
	public function __construct(manager $manager)
25
	{
26
		$this->tools = $manager->get_tools();
27
	}
28
29
	/**
30
	 * Trim and clean text
31
	 *
32
	 * @param string $message Message text
33
	 * @param int    $length  The length to trim text to
34
	 * @return string Trimmed message text
35
	 * @access protected
36
	 */
37
	public function trim_text($message, $length)
38
	{
39
		// display smileys as text :)
40
		$message = smiley_text($message, true);
41
42
		// run the text through our trim tools (they filter out bbcodes and other markup)
43
		/** @var tools\tool_interface $tool */
44
		foreach ($this->tools as $tool)
45
		{
46
			$message = $tool->set_text($message)->run();
47
		}
48
49
		if (utf8_strlen($message) <= $length)
50
		{
51
			return $this->tp_nl2br($message);
52
		}
53
54
		// trim the text to the last whitespace character before the cut-off
55
		$message = preg_replace('/\s+?(\S+)?$/', '', utf8_substr($message, 0, $length));
56
57
		return $this->tp_nl2br($message) . '...';
58
	}
59
60
	/**
61
	 * Convert and preserve line breaks
62
	 * http://stackoverflow.com/questions/816085/removing-redundant-line-breaks-with-regular-expressions
63
	 *
64
	 * @param string $message Message text
65
	 * @return string Message text with line breaks
66
	 * @access protected
67
	 */
68
	protected function tp_nl2br($message)
69
	{
70
		return nl2br(preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $message));
71
	}
72
}
73