| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648 |
- <?php
- namespace Tools\View\Helper;
- use Cake\Core\Configure;
- use Cake\View\Helper;
- use Cake\View\StringTemplate;
- use Cake\View\View;
- use RuntimeException;
- use Shim\Utility\Inflector as ShimInflector;
- /**
- * Format helper with basic HTML snippets
- *
- * @author Mark Scherer
- * @license MIT
- * @property \Cake\View\Helper\HtmlHelper $Html
- * @property \Tools\View\Helper\IconHelper $Icon
- */
- class FormatHelper extends Helper {
- /**
- * Other helpers used by FormHelper
- *
- * @var array
- */
- protected array $helpers = ['Html', 'Tools.Icon'];
- /**
- * @var \Cake\View\StringTemplate
- */
- protected $template;
- /**
- * @var array
- */
- protected array $_defaultIcons = [
- 'yes' => 'fa fa-check',
- 'no' => 'fa fa-times',
- 'view' => 'fa fa-eye',
- 'edit' => 'fa fa-pen',
- 'add' => 'fa fa-plus',
- 'delete' => 'fa fa-trash',
- 'prev' => 'fa fa-arrow-left',
- 'next' => 'fa fa-arrow-right',
- 'pro' => 'fa fa-thumbs-up',
- 'contra' => 'fa fa-thumbs-down',
- 'male' => 'fa fa-mars',
- 'female' => 'fa fa-venus',
- 'config' => 'fa fa-cogs',
- 'login' => 'fa fa-sign-in-alt',
- 'logout' => 'fa fa-sign-out-alt',
- ];
- /**
- * @var array
- */
- protected array $_defaults = [
- 'fontIcons' => null,
- 'iconNamespaces' => [], // Used to disable auto prefixing if detected
- 'iconNamespace' => 'fa', // Used to be icon,
- 'autoPrefix' => true, // For custom icons "prev" becomes "fa-prev" when iconNamespace is "fa"
- 'templates' => [
- 'icon' => '<i class="{{class}}"{{attributes}}></i>',
- 'ok' => '<span class="ok-{{type}}" style="color:{{color}}"{{attributes}}>{{content}}</span>',
- ],
- 'slugger' => null,
- 'iconHelper' => false, // FC with new Icon helper
- ];
- /**
- * @param \Cake\View\View $View
- * @param array<string, mixed> $config
- */
- public function __construct(View $View, array $config = []) {
- $defaults = (array)Configure::read('Format') + $this->_defaults;
- $config += $defaults;
- $config['fontIcons'] = (array)$config['fontIcons'] + $this->_defaultIcons;
- $this->template = new StringTemplate($config['templates']);
- parent::__construct($View, $config);
- }
- /**
- * jqueryAccess: {id}Pro, {id}Contra
- *
- * @param mixed $value Boolish value
- * @param array<string, mixed> $options
- * @param array<string, mixed> $attributes
- * @return string
- */
- public function thumbs($value, array $options = [], array $attributes = []) {
- $icon = !empty($value) ? 'pro' : 'contra';
- return $this->Icon->render($icon, $options, $attributes);
- }
- /**
- * Display neighbor quicklinks
- *
- * @param array $neighbors (containing prev and next)
- * @param string $field Field as `Field` or `Model.field` syntax
- * @param array<string, mixed> $options :
- * - name: title name: next{Record} (if none is provided, "record" is used - not translated!)
- * - slug: true/false (defaults to false)
- * - titleField: field or `Model.field`
- * @return string
- */
- public function neighbors(array $neighbors, $field, array $options = []) {
- $name = 'Record'; // Translation further down!
- if (!empty($options['name'])) {
- $name = ucfirst($options['name']);
- }
- $prevSlug = $nextSlug = null;
- if (!empty($options['slug'])) {
- if (!empty($neighbors['prev'])) {
- $prevSlug = $this->slug($neighbors['prev'][$field]);
- }
- if (!empty($neighbors['next'])) {
- $nextSlug = $this->slug($neighbors['next'][$field]);
- }
- }
- $titleField = $field;
- if (!empty($options['titleField'])) {
- $titleField = $options['titleField'];
- }
- if (!isset($options['escape']) || $options['escape'] === false) {
- $titleField = h($titleField);
- }
- $ret = '<div class="next-prev-navi nextPrevNavi">';
- if (!empty($neighbors['prev'])) {
- $url = [$neighbors['prev']['id'], $prevSlug];
- if (!empty($options['url'])) {
- $url += $options['url'];
- }
- $ret .= $this->Html->link(
- $this->Icon->render('prev') . ' ' . __d('tools', 'prev' . $name),
- $url,
- ['escape' => false, 'title' => $neighbors['prev'][$titleField]],
- );
- } else {
- $ret .= $this->Icon->render('prev');
- }
- $ret .= ' ';
- if (!empty($neighbors['next'])) {
- $url = [$neighbors['next']['id'], $nextSlug];
- if (!empty($options['url'])) {
- $url += $options['url'];
- }
- $ret .= $this->Html->link(
- $this->Icon->render('next') . ' ' . __d('tools', 'next' . $name),
- $url,
- ['escape' => false, 'title' => $neighbors['next'][$titleField]],
- );
- } else {
- $ret .= $this->Icon->render('next') . ' ' . __d('tools', 'next' . $name);
- }
- $ret .= '</div>';
- return $ret;
- }
- /**
- * @var int
- */
- public const GENDER_FEMALE = 2;
- /**
- * @var int
- */
- public const GENDER_MALE = 1;
- /**
- * Displays gender icon
- *
- * @param string|int $value
- * @param array<string, mixed> $options
- * @param array<string, mixed> $attributes
- * @return string
- */
- public function genderIcon($value, array $options = [], array $attributes = []) {
- $value = (int)$value;
- if ($value == static::GENDER_FEMALE) {
- $icon = $this->Icon->render('female', $options, $attributes);
- } elseif ($value == static::GENDER_MALE) {
- $icon = $this->Icon->render('male', $options, $attributes);
- } else {
- $icon = $this->Icon->render('genderless', $options, $attributes + ['title' => __d('tools', 'Inter')]);
- }
- return $icon;
- }
- /**
- * Img Icons
- *
- * @param string $icon (constant or filename)
- * @param array<string, mixed> $options :
- * - translate, title, ...
- * @param array<string, mixed> $attributes :
- * - class, ...
- * @return string
- */
- public function cIcon($icon, array $options = [], array $attributes = []) {
- return $this->_customIcon($icon, $options, $attributes);
- }
- /**
- * Deprecated img icons, font icons should be used instead, but sometimes
- * we still need a custom img icon.
- *
- * @param string $icon (constant or filename)
- * @param array<string, mixed> $options :
- * - translate, title, ...
- * @param array<string, mixed> $attributes :
- * - class, ...
- * @return string
- */
- protected function _customIcon($icon, array $options = [], array $attributes = []) {
- $translate = $options['translate'] ?? true;
- $type = pathinfo($icon, PATHINFO_FILENAME);
- $title = ucfirst($type);
- $alt = $this->slug($title);
- if ($translate !== false) {
- $title = __($title);
- $alt = __($alt);
- }
- $alt = '[' . $alt . ']';
- $defaults = ['title' => $title, 'alt' => $alt, 'class' => 'icon'];
- $options = $attributes + $options;
- $options += $defaults;
- if (substr($icon, 0, 1) !== '/') {
- $icon = 'icons/' . $icon;
- }
- return $this->Html->image($icon, $options);
- }
- /**
- * Renders a font icon.
- *
- * @param string $type
- * @param array<string, mixed> $options
- * @param array<string, mixed> $attributes
- * @return string
- */
- protected function _fontIcon($type, $options, $attributes) {
- $iconClass = $type;
- unset($this->_config['class']);
- $options += $this->_config;
- if ($options['autoPrefix'] && is_string($options['autoPrefix'])) {
- $iconClass = $options['autoPrefix'] . '-' . $iconClass;
- } elseif ($options['autoPrefix'] && $options['iconNamespace']) {
- $iconClass = $options['iconNamespace'] . '-' . $iconClass;
- }
- if ($options['iconNamespace']) {
- $iconClass = $options['iconNamespace'] . ' ' . $iconClass;
- }
- if (isset($this->_config['fontIcons'][$type])) {
- $iconClass = $this->_config['fontIcons'][$type];
- }
- $defaults = [
- 'class' => 'icon icon-' . $type . ' ' . $iconClass,
- 'escape' => true,
- ];
- $options += $defaults;
- if (!isset($attributes['title'])) {
- $attributes['title'] = ucfirst($type);
- }
- if (!isset($options['translate']) || $options['translate'] !== false) {
- $attributes['title'] = __($attributes['title']);
- }
- if (isset($attributes['class'])) {
- $options['class'] .= ' ' . $attributes['class'];
- unset($attributes['class']);
- }
- $attributes += [
- 'data-placement' => 'bottom',
- 'data-toggle' => 'tooltip',
- ];
- $formatOptions = $attributes + [
- 'escape' => $options['escape'],
- ];
- $options['attributes'] = $this->template->formatAttributes($formatOptions);
- return $this->template->format('icon', $options);
- }
- /**
- * Displays yes/no symbol.
- *
- * @param int|bool $value Value
- * @param array<string, mixed> $options
- * - on (defaults to 1/true)
- * - onTitle
- * - offTitle
- * @param array<string, mixed> $attributes
- * - title, ...
- * @return string HTML icon Yes/No
- */
- public function yesNo($value, array $options = [], array $attributes = []) {
- $defaults = [
- 'on' => 1,
- 'onTitle' => __d('tools', 'Yes'),
- 'offTitle' => __d('tools', 'No'),
- ];
- $options += $defaults;
- if ($value == $options['on']) {
- $icon = 'yes';
- $value = 'on';
- } else {
- $icon = 'no';
- $value = 'off';
- }
- $attributes += ['title' => $options[$value . 'Title']];
- return $this->Icon->render($icon, $options, $attributes);
- }
- /**
- * Gets URL of a png img of a website (16x16 pixel).
- *
- * @param string $domain
- * @return string
- */
- public function siteIconUrl($domain) {
- if (strpos($domain, 'http') === 0) {
- // Strip protocol
- $pieces = parse_url($domain);
- if ($pieces !== false) {
- $domain = $pieces['host'];
- }
- }
- return 'http://www.google.com/s2/favicons?domain=' . $domain;
- }
- /**
- * Display a png img of a website (16x16 pixel)
- * if not available, will return a fallback image (a globe)
- *
- * @param string $domain (preferably without protocol, e.g. "www.site.com")
- * @param array<string, mixed> $options
- * @return string
- */
- public function siteIcon($domain, array $options = []) {
- $url = $this->siteIconUrl($domain);
- $options['width'] = 16;
- $options['height'] = 16;
- if (!isset($options['alt'])) {
- $options['alt'] = $domain;
- }
- if (!isset($options['title'])) {
- $options['title'] = $domain;
- }
- return $this->Html->image($url, $options);
- }
- /**
- * Display a disabled link tag
- *
- * @param string $text
- * @param array<string, mixed> $options
- * @return string
- */
- public function disabledLink($text, array $options = []) {
- $defaults = ['class' => 'disabledLink', 'title' => __d('tools', 'notAvailable')];
- $options += $defaults;
- return $this->Html->tag('span', $text, $options);
- }
- /**
- * Fixes utf8 problems of native php str_pad function
- * //TODO: move to textext helper? Also note there is Text::wrap() now.
- *
- * @param string $input
- * @param int $padLength
- * @param string $padString
- * @param mixed $padType
- * @return string input
- */
- public function pad($input, $padLength, $padString, $padType = STR_PAD_RIGHT) {
- $length = mb_strlen($input);
- if ($padLength - $length > 0) {
- switch ($padType) {
- case STR_PAD_LEFT:
- $input = str_repeat($padString, $padLength - $length) . $input;
- break;
- case STR_PAD_RIGHT:
- $input .= str_repeat($padString, $padLength - $length);
- break;
- }
- }
- return $input;
- }
- /**
- * Returns red colored if not ok
- *
- * @param string $value
- * @param mixed $ok Boolish value
- * @return string Value in HTML tags
- */
- public function warning($value, $ok = false) {
- if (!$ok) {
- return $this->ok($value, false);
- }
- return $value;
- }
- /**
- * Returns green on ok, red otherwise
- *
- * @todo Remove inline css and make classes better: green=>ok red=>not-ok
- * Maybe use templating
- *
- * @param mixed $content Output
- * @param bool $ok Boolish value
- * @param array<string, mixed> $attributes
- * @return string Value nicely formatted/colored
- */
- public function ok($content, $ok = false, array $attributes = []) {
- if ($ok) {
- $type = 'yes';
- $color = 'green';
- } else {
- $type = 'no';
- $color = 'red';
- }
- $options = [
- 'type' => $type,
- 'color' => $color,
- ];
- $options['content'] = $content;
- $options['attributes'] = $this->template->formatAttributes($attributes);
- return $this->template->format('ok', $options);
- }
- /**
- * Prepared string for output inside `<pre>...</pre>`.
- *
- * @param string $text
- * @param array $options
- *
- * @return string
- */
- public function pre(string $text, array $options = []): string {
- $options += [
- 'escape' => true,
- 'space' => 4,
- ];
- if ($options['escape']) {
- $text = h($text);
- }
- $text = str_replace("\t", str_repeat(' ', $options['space']), $text);
- return $text;
- }
- /**
- * Useful for displaying tabbed (code) content when the default of 8 spaces
- * inside <pre> is too much. This converts it to spaces for better output.
- *
- * Inspired by the tab2space function found at:
- *
- * @see http://aidan.dotgeek.org/lib/?file=function.tab2space.php
- * @param string $text
- * @param int $spaces
- * @return string
- */
- public function tab2space($text, $spaces = 4) {
- $spacesString = str_repeat(' ', $spaces);
- $splitText = preg_split("/\r\n|\r|\n/", trim($text));
- if ($splitText === false) {
- return $text;
- }
- $wordLengths = [];
- $wArray = [];
- // Store word lengths
- foreach ($splitText as $line) {
- $words = preg_split("/(\t+)/", $line, -1, PREG_SPLIT_DELIM_CAPTURE);
- foreach (array_keys($words) as $i) {
- $strlen = strlen($words[$i]);
- $add = isset($wordLengths[$i]) && ($wordLengths[$i] < $strlen);
- if ($add || !isset($wordLengths[$i])) {
- $wordLengths[$i] = $strlen;
- }
- }
- $wArray[] = $words;
- }
- $text = '';
- // Apply padding when appropriate and rebuild the string
- foreach (array_keys($wArray) as $i) {
- foreach (array_keys($wArray[$i]) as $ii) {
- if (preg_match("/^\t+$/", $wArray[$i][$ii])) {
- $wArray[$i][$ii] = str_pad($wArray[$i][$ii], $wordLengths[$ii], "\t");
- } else {
- $wArray[$i][$ii] = str_pad($wArray[$i][$ii], $wordLengths[$ii]);
- }
- }
- $text .= str_replace("\t", $spacesString, implode('', $wArray[$i])) . "\n";
- }
- return $text;
- }
- /**
- * Translate a result array into a HTML table
- *
- * @todo Move to Text Helper etc.
- *
- * Options:
- * - recursive: Recursively generate tables for multi-dimensional arrays
- * - heading: Display the first as heading row (th)
- * - escape: Defaults to true
- * - null: Null value
- *
- * @author Aidan Lister <aidan@php.net>
- * @version 1.3.2
- * @link http://aidanlister.com/2004/04/converting-arrays-to-human-readable-tables/
- * @param array $array The result (numericaly keyed, associative inner) array.
- * @param array<string, mixed> $options
- * @param array<string, mixed> $attributes For the table
- * @return string
- */
- public function array2table(array $array, array $options = [], array $attributes = []) {
- $defaults = [
- 'null' => ' ',
- 'recursive' => false,
- 'heading' => true,
- 'escape' => true,
- ];
- $options += $defaults;
- // Sanity check
- if (!$array) {
- return '';
- }
- if (!isset($array[0]) || !is_array($array[0])) {
- $array = [$array];
- }
- $attributes += [
- 'class' => 'table',
- ];
- $attributes = $this->template->formatAttributes($attributes);
- // Start the table
- $table = "<table$attributes>\n";
- if ($options['heading']) {
- // The header
- $table .= "\t<tr>";
- // Take the keys from the first row as the headings
- foreach (array_keys($array[0]) as $heading) {
- $table .= '<th>' . ($options['escape'] ? h($heading) : $heading) . '</th>';
- }
- $table .= "</tr>\n";
- }
- // The body
- foreach ($array as $row) {
- $table .= "\t<tr>";
- foreach ($row as $cell) {
- $table .= '<td>';
- // Cast objects
- if (is_object($cell)) {
- $cell = (array)$cell;
- }
- if ($options['recursive'] && is_array($cell) && !empty($cell)) {
- // Recursive mode
- $table .= "\n" . static::array2table($cell, $options) . "\n";
- } else {
- $table .= (!is_array($cell) && strlen($cell) > 0) ? ($options['escape'] ? h(
- $cell,
- ) : $cell) : $options['null'];
- }
- $table .= '</td>';
- }
- $table .= "</tr>\n";
- }
- $table .= '</table>';
- return $table;
- }
- /**
- * @param string $string
- *
- * @throws \RuntimeException
- * @return string
- */
- public function slug($string) {
- if ($this->_config['slugger']) {
- $callable = $this->_config['slugger'];
- if (!is_callable($callable)) {
- throw new RuntimeException('Invalid callable passed as slugger.');
- }
- return $callable($string);
- }
- return ShimInflector::slug($string);
- }
- }
|