Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
TruncateFilter.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
11 use Magento\Framework\Filter\TruncateFilter\ResultFactory;
12 
20 {
24  private $length;
25 
29  private $etc;
30 
34  private $breakWords;
35 
39  private $stringUtils;
40 
44  private $resultFactory;
45 
53  public function __construct(
54  \Magento\Framework\Stdlib\StringUtils $stringUtils,
55  ResultFactory $resultFactory,
56  $length = 80,
57  $etc = '...',
58  $breakWords = true
59  ) {
60  $this->stringUtils = $stringUtils;
61  $this->resultFactory = $resultFactory;
62  $this->length = $length;
63  $this->etc = $etc;
64  $this->breakWords = $breakWords;
65  }
66 
73  public function filter($string) : Result
74  {
76  $result = $this->resultFactory->create(['value' => $string, 'remainder' => '']);
77  $length = $this->length;
78  if (0 == $length) {
79  $result->setValue('');
80  return $result;
81  }
82 
83  $originalLength = $this->stringUtils->strlen($string);
84  if ($originalLength > $length) {
85  $length -= $this->stringUtils->strlen($this->etc);
86  if ($length <= 0) {
87  $result->setValue('');
88  return $result;
89  }
90  $preparedString = $string;
91  $preparedLength = $length;
92  if (!$this->breakWords) {
93  $preparedString = preg_replace(
94  '/\s+?(\S+)?$/u',
95  '',
96  $this->stringUtils->substr($string, 0, $length + 1)
97  );
98  $preparedLength = $this->stringUtils->strlen($preparedString);
99  }
100  $result->setRemainder($this->stringUtils->substr($string, $preparedLength, $originalLength));
101  $result->setValue($this->stringUtils->substr($preparedString, 0, $length) . $this->etc);
102  return $result;
103  }
104 
105  return $result;
106  }
107 }
__construct(\Magento\Framework\Stdlib\StringUtils $stringUtils, ResultFactory $resultFactory, $length=80, $etc='...', $breakWords=true)