CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Team
    • Issues (Github)
    • YouTube Channel
    • Get Involved
    • Bakery
    • Featured Resources
    • Newsletter
    • Certification
    • My CakePHP
    • CakeFest
    • Facebook
    • Twitter
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.8 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.8
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Namespaces

  • Cake
    • Auth
      • Storage
    • Cache
      • Engine
    • Collection
      • Iterator
    • Command
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
      • Retry
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
      • Middleware
    • Event
      • Decorator
    • Filesystem
    • Form
    • Http
      • Client
        • Adapter
        • Auth
      • Cookie
      • Exception
      • Middleware
      • Session
    • I18n
      • Formatter
      • Middleware
      • Parser
    • Log
      • Engine
    • Mailer
      • Exception
      • Transport
    • Network
      • Exception
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Locator
      • Rule
    • Routing
      • Exception
      • Filter
      • Middleware
      • Route
    • Shell
      • Helper
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • BreadcrumbsHelper
  • FlashHelper
  • FormHelper
  • HtmlHelper
  • NumberHelper
  • PaginatorHelper
  • RssHelper
  • SessionHelper
  • TextHelper
  • TimeHelper
  • UrlHelper

Traits

  • IdGeneratorTrait
  • SecureFieldTokenTrait
  1: <?php
  2: /**
  3:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5:  *
  6:  * Licensed under The MIT License
  7:  * For full copyright and license information, please see the LICENSE.txt
  8:  * Redistributions of files must retain the above copyright notice.
  9:  *
 10:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 11:  * @link          https://cakephp.org CakePHP(tm) Project
 12:  * @since         0.10.0
 13:  * @license       https://opensource.org/licenses/mit-license.php MIT License
 14:  */
 15: namespace Cake\View\Helper;
 16: 
 17: use Cake\Core\App;
 18: use Cake\Core\Exception\Exception;
 19: use Cake\Utility\Security;
 20: use Cake\View\Helper;
 21: use Cake\View\View;
 22: 
 23: /**
 24:  * Text helper library.
 25:  *
 26:  * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
 27:  *
 28:  * @property \Cake\View\Helper\HtmlHelper $Html
 29:  * @link https://book.cakephp.org/3.0/en/views/helpers/text.html
 30:  * @see \Cake\Utility\Text
 31:  */
 32: class TextHelper extends Helper
 33: {
 34:     /**
 35:      * helpers
 36:      *
 37:      * @var array
 38:      */
 39:     public $helpers = ['Html'];
 40: 
 41:     /**
 42:      * Default config for this class
 43:      *
 44:      * @var array
 45:      */
 46:     protected $_defaultConfig = [
 47:         'engine' => 'Cake\Utility\Text'
 48:     ];
 49: 
 50:     /**
 51:      * An array of hashes and their contents.
 52:      * Used when inserting links into text.
 53:      *
 54:      * @var array
 55:      */
 56:     protected $_placeholders = [];
 57: 
 58:     /**
 59:      * Cake Utility Text instance
 60:      *
 61:      * @var \Cake\Utility\Text
 62:      */
 63:     protected $_engine;
 64: 
 65:     /**
 66:      * Constructor
 67:      *
 68:      * ### Settings:
 69:      *
 70:      * - `engine` Class name to use to replace String functionality.
 71:      *            The class needs to be placed in the `Utility` directory.
 72:      *
 73:      * @param \Cake\View\View $View the view object the helper is attached to.
 74:      * @param array $config Settings array Settings array
 75:      * @throws \Cake\Core\Exception\Exception when the engine class could not be found.
 76:      */
 77:     public function __construct(View $View, array $config = [])
 78:     {
 79:         parent::__construct($View, $config);
 80: 
 81:         $config = $this->_config;
 82:         $engineClass = App::className($config['engine'], 'Utility');
 83:         if ($engineClass) {
 84:             $this->_engine = new $engineClass($config);
 85:         } else {
 86:             throw new Exception(sprintf('Class for %s could not be found', $config['engine']));
 87:         }
 88:     }
 89: 
 90:     /**
 91:      * Call methods from String utility class
 92:      *
 93:      * @param string $method Method to invoke
 94:      * @param array $params Array of params for the method.
 95:      * @return mixed Whatever is returned by called method, or false on failure
 96:      */
 97:     public function __call($method, $params)
 98:     {
 99:         return call_user_func_array([$this->_engine, $method], $params);
100:     }
101: 
102:     /**
103:      * Adds links (<a href=....) to a given text, by finding text that begins with
104:      * strings like http:// and ftp://.
105:      *
106:      * ### Options
107:      *
108:      * - `escape` Control HTML escaping of input. Defaults to true.
109:      *
110:      * @param string $text Text
111:      * @param array $options Array of HTML options, and options listed above.
112:      * @return string The text with links
113:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#linking-urls
114:      */
115:     public function autoLinkUrls($text, array $options = [])
116:     {
117:         $this->_placeholders = [];
118:         $options += ['escape' => true];
119: 
120:         $pattern = '/(?:(?<!href="|src="|">)
121:             (?>
122:                 (
123:                     (?<left>[\[<(]) # left paren,brace
124:                     (?>
125:                         # Lax match URL
126:                         (?<url>(?:https?|ftp|nntp):\/\/[\p{L}0-9.\-_:]+(?:[\/?][\p{L}0-9.\-_:\/?=&>\[\]\(\)\#\@\+~!;,%]+[^-_:?>\[\(\@\+~!;<,.%\s])?)
127:                         (?<right>[\])>]) # right paren,brace
128:                     )
129:                 )
130:                 |
131:                 (?<url_bare>(?P>url)) # A bare URL. Use subroutine
132:             )
133:             )/ixu';
134: 
135:         $text = preg_replace_callback(
136:             $pattern,
137:             [&$this, '_insertPlaceHolder'],
138:             $text
139:         );
140:         $text = preg_replace_callback(
141:             '#(?<!href="|">)(?<!\b[[:punct:]])(?<!http://|https://|ftp://|nntp://)www\.[^\s\n\%\ <]+[^\s<\n\%\,\.\ <](?<!\))#i',
142:             [&$this, '_insertPlaceHolder'],
143:             $text
144:         );
145:         if ($options['escape']) {
146:             $text = h($text);
147:         }
148: 
149:         return $this->_linkUrls($text, $options);
150:     }
151: 
152:     /**
153:      * Saves the placeholder for a string, for later use. This gets around double
154:      * escaping content in URL's.
155:      *
156:      * @param array $matches An array of regexp matches.
157:      * @return string Replaced values.
158:      */
159:     protected function _insertPlaceHolder($matches)
160:     {
161:         $match = $matches[0];
162:         $envelope = ['', ''];
163:         if (isset($matches['url'])) {
164:             $match = $matches['url'];
165:             $envelope = [$matches['left'], $matches['right']];
166:         }
167:         if (isset($matches['url_bare'])) {
168:             $match = $matches['url_bare'];
169:         }
170:         $key = hash_hmac('sha1', $match, Security::getSalt());
171:         $this->_placeholders[$key] = [
172:             'content' => $match,
173:             'envelope' => $envelope
174:         ];
175: 
176:         return $key;
177:     }
178: 
179:     /**
180:      * Replace placeholders with links.
181:      *
182:      * @param string $text The text to operate on.
183:      * @param array $htmlOptions The options for the generated links.
184:      * @return string The text with links inserted.
185:      */
186:     protected function _linkUrls($text, $htmlOptions)
187:     {
188:         $replace = [];
189:         foreach ($this->_placeholders as $hash => $content) {
190:             $link = $url = $content['content'];
191:             $envelope = $content['envelope'];
192:             if (!preg_match('#^[a-z]+\://#i', $url)) {
193:                 $url = 'http://' . $url;
194:             }
195:             $replace[$hash] = $envelope[0] . $this->Html->link($link, $url, $htmlOptions) . $envelope[1];
196:         }
197: 
198:         return strtr($text, $replace);
199:     }
200: 
201:     /**
202:      * Links email addresses
203:      *
204:      * @param string $text The text to operate on
205:      * @param array $options An array of options to use for the HTML.
206:      * @return string
207:      * @see \Cake\View\Helper\TextHelper::autoLinkEmails()
208:      */
209:     protected function _linkEmails($text, $options)
210:     {
211:         $replace = [];
212:         foreach ($this->_placeholders as $hash => $content) {
213:             $url = $content['content'];
214:             $envelope = $content['envelope'];
215:             $replace[$hash] = $envelope[0] . $this->Html->link($url, 'mailto:' . $url, $options) . $envelope[1];
216:         }
217: 
218:         return strtr($text, $replace);
219:     }
220: 
221:     /**
222:      * Adds email links (<a href="mailto:....) to a given text.
223:      *
224:      * ### Options
225:      *
226:      * - `escape` Control HTML escaping of input. Defaults to true.
227:      *
228:      * @param string $text Text
229:      * @param array $options Array of HTML options, and options listed above.
230:      * @return string The text with links
231:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#linking-email-addresses
232:      */
233:     public function autoLinkEmails($text, array $options = [])
234:     {
235:         $options += ['escape' => true];
236:         $this->_placeholders = [];
237: 
238:         $atom = '[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]';
239:         $text = preg_replace_callback(
240:             '/(?<=\s|^|\(|\>|\;)(' . $atom . '*(?:\.' . $atom . '+)*@[\p{L}0-9-]+(?:\.[\p{L}0-9-]+)+)/ui',
241:             [&$this, '_insertPlaceholder'],
242:             $text
243:         );
244:         if ($options['escape']) {
245:             $text = h($text);
246:         }
247: 
248:         return $this->_linkEmails($text, $options);
249:     }
250: 
251:     /**
252:      * Convert all links and email addresses to HTML links.
253:      *
254:      * ### Options
255:      *
256:      * - `escape` Control HTML escaping of input. Defaults to true.
257:      *
258:      * @param string $text Text
259:      * @param array $options Array of HTML options, and options listed above.
260:      * @return string The text with links
261:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#linking-both-urls-and-email-addresses
262:      */
263:     public function autoLink($text, array $options = [])
264:     {
265:         $text = $this->autoLinkUrls($text, $options);
266: 
267:         return $this->autoLinkEmails($text, ['escape' => false] + $options);
268:     }
269: 
270:     /**
271:      * Highlights a given phrase in a text. You can specify any expression in highlighter that
272:      * may include the \1 expression to include the $phrase found.
273:      *
274:      * @param string $text Text to search the phrase in
275:      * @param string $phrase The phrase that will be searched
276:      * @param array $options An array of HTML attributes and options.
277:      * @return string The highlighted text
278:      * @see \Cake\Utility\Text::highlight()
279:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#highlighting-substrings
280:      */
281:     public function highlight($text, $phrase, array $options = [])
282:     {
283:         return $this->_engine->highlight($text, $phrase, $options);
284:     }
285: 
286:     /**
287:      * Formats paragraphs around given text for all line breaks
288:      *  <br /> added for single line return
289:      *  <p> added for double line return
290:      *
291:      * @param string $text Text
292:      * @return string The text with proper <p> and <br /> tags
293:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#converting-text-into-paragraphs
294:      */
295:     public function autoParagraph($text)
296:     {
297:         if (trim($text) !== '') {
298:             $text = preg_replace('|<br[^>]*>\s*<br[^>]*>|i', "\n\n", $text . "\n");
299:             $text = preg_replace("/\n\n+/", "\n\n", str_replace(["\r\n", "\r"], "\n", $text));
300:             $texts = preg_split('/\n\s*\n/', $text, -1, PREG_SPLIT_NO_EMPTY);
301:             $text = '';
302:             foreach ($texts as $txt) {
303:                 $text .= '<p>' . nl2br(trim($txt, "\n")) . "</p>\n";
304:             }
305:             $text = preg_replace('|<p>\s*</p>|', '', $text);
306:         }
307: 
308:         return $text;
309:     }
310: 
311:     /**
312:      * Strips given text of all links (<a href=....)
313:      *
314:      * @param string $text Text
315:      * @return string The text without links
316:      * @see \Cake\Utility\Text::stripLinks()
317:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#removing-links
318:      */
319:     public function stripLinks($text)
320:     {
321:         return $this->_engine->stripLinks($text);
322:     }
323: 
324:     /**
325:      * Truncates text.
326:      *
327:      * Cuts a string to the length of $length and replaces the last characters
328:      * with the ellipsis if the text is longer than length.
329:      *
330:      * ### Options:
331:      *
332:      * - `ellipsis` Will be used as Ending and appended to the trimmed string
333:      * - `exact` If false, $text will not be cut mid-word
334:      * - `html` If true, HTML tags would be handled correctly
335:      *
336:      * @param string $text String to truncate.
337:      * @param int $length Length of returned string, including ellipsis.
338:      * @param array $options An array of HTML attributes and options.
339:      * @return string Trimmed string.
340:      * @see \Cake\Utility\Text::truncate()
341:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#truncating-text
342:      */
343:     public function truncate($text, $length = 100, array $options = [])
344:     {
345:         return $this->_engine->truncate($text, $length, $options);
346:     }
347: 
348:     /**
349:      * Truncates text starting from the end.
350:      *
351:      * Cuts a string to the length of $length and replaces the first characters
352:      * with the ellipsis if the text is longer than length.
353:      *
354:      * ### Options:
355:      *
356:      * - `ellipsis` Will be used as Beginning and prepended to the trimmed string
357:      * - `exact` If false, $text will not be cut mid-word
358:      *
359:      * @param string $text String to truncate.
360:      * @param int $length Length of returned string, including ellipsis.
361:      * @param array $options An array of HTML attributes and options.
362:      * @return string Trimmed string.
363:      * @see \Cake\Utility\Text::tail()
364:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#truncating-the-tail-of-a-string
365:      */
366:     public function tail($text, $length = 100, array $options = [])
367:     {
368:         return $this->_engine->tail($text, $length, $options);
369:     }
370: 
371:     /**
372:      * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
373:      * determined by radius.
374:      *
375:      * @param string $text String to search the phrase in
376:      * @param string $phrase Phrase that will be searched for
377:      * @param int $radius The amount of characters that will be returned on each side of the founded phrase
378:      * @param string $ending Ending that will be appended
379:      * @return string Modified string
380:      * @see \Cake\Utility\Text::excerpt()
381:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#extracting-an-excerpt
382:      */
383:     public function excerpt($text, $phrase, $radius = 100, $ending = '...')
384:     {
385:         return $this->_engine->excerpt($text, $phrase, $radius, $ending);
386:     }
387: 
388:     /**
389:      * Creates a comma separated list where the last two items are joined with 'and', forming natural language.
390:      *
391:      * @param string[] $list The list to be joined.
392:      * @param string|null $and The word used to join the last and second last items together with. Defaults to 'and'.
393:      * @param string $separator The separator used to join all the other items together. Defaults to ', '.
394:      * @return string The glued together string.
395:      * @see \Cake\Utility\Text::toList()
396:      * @link https://book.cakephp.org/3.0/en/views/helpers/text.html#converting-an-array-to-sentence-form
397:      */
398:     public function toList($list, $and = null, $separator = ', ')
399:     {
400:         return $this->_engine->toList($list, $and, $separator);
401:     }
402: 
403:     /**
404:      * Event listeners.
405:      *
406:      * @return array
407:      */
408:     public function implementedEvents()
409:     {
410:         return [];
411:     }
412: }
413: 
Follow @CakePHP
#IRC
OpenHub
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Logos & Trademarks
  • Community
  • Team
  • Issues (Github)
  • YouTube Channel
  • Get Involved
  • Bakery
  • Featured Resources
  • Newsletter
  • Certification
  • My CakePHP
  • CakeFest
  • Facebook
  • Twitter
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs