Completed
Push — master ( 494091...32c874 )
by David
27s
created

PluginTruncate::process()   B

Complexity

Conditions 6
Paths 6

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 24
Code Lines 14

Importance

Changes 0
Metric Value
cc 6
eloc 14
nc 6
nop 5
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
1
<?php
2
/**
3
 * Copyright (c) 2013-2017
4
 *
5
 * @category  Library
6
 * @package   Dwoo\Plugins\Functions
7
 * @author    Jordi Boggiano <[email protected]>
8
 * @author    David Sanchez <[email protected]>
9
 * @copyright 2008-2013 Jordi Boggiano
10
 * @copyright 2013-2017 David Sanchez
11
 * @license   http://dwoo.org/LICENSE Modified BSD License
12
 * @version   1.3.2
13
 * @date      2017-01-06
14
 * @link      http://dwoo.org/
15
 */
16
17
namespace Dwoo\Plugins\Functions;
18
19
use Dwoo\Plugin;
20
21
/**
22
 * Truncates a string at the given length
23
 * <pre>
24
 *  * value : text to truncate
25
 *  * length : the maximum length for the string
26
 *  * etc : the characters that are added to show that the string was cut off
27
 *  * break : if true, the string will be cut off at the exact length, instead of cutting at the nearest space
28
 *  * middle : if true, the string will contain the beginning and the end, and the extra characters will be removed
29
 *  from the middle
30
 * </pre>
31
 * This software is provided 'as-is', without any express or implied warranty.
32
 * In no event will the authors be held liable for any damages arising from the use of this software.
33
 */
34
class PluginTruncate extends Plugin
35
{
36
    /**
37
     * @param string $value
38
     * @param int    $length
39
     * @param string $etc
40
     * @param bool   $break
41
     * @param bool   $middle
42
     *
43
     * @return mixed|string
44
     */
45
    public function process($value, $length = 80, $etc = '...', $break = false, $middle = false)
46
    {
47
        if ($length == 0) {
48
            return '';
49
        }
50
51
        $value  = (string)$value;
52
        $etc    = (string)$etc;
53
        $length = (int)$length;
54
55
        if (strlen($value) < $length) {
56
            return $value;
57
        }
58
59
        $length = max($length - strlen($etc), 0);
60
        if ($break === false && $middle === false) {
61
            $value = preg_replace('#\s+(\S*)?$#', '', substr($value, 0, $length + 1));
62
        }
63
        if ($middle === false) {
64
            return substr($value, 0, $length) . $etc;
65
        }
66
67
        return substr($value, 0, ceil($length / 2)) . $etc . substr($value, - floor($length / 2));
68
    }
69
}