Completed
Pull Request — master (#28)
by Matt
02:49
created

trim_tools::remove_bbcode_contents()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 23
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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