View file Upload/src/addons/Brivium/CustomNodeIcon/Listener.php

File size: 1.96Kb
<?php

namespace Brivium\CustomNodeIcon;

use XF\Entity\Node;

class Listener
{
    public static function templaterSetup(\XF\Container $container, \XF\Template\Templater &$templater)
    {
        $templater->addFunction('brcin_node_icon', function (\XF\Template\Templater $templater, &$escape, Node $node, $type, $ignoreDefault = false, $attributes = [], $default = '')
        {
            $iconUrl = $node->getIconUrlByType($type, $ignoreDefault);
            if(empty($iconUrl)) {
                return $default;
            }

            $typeClass = "brcni-node-icon-{$node->node_id}-{$type}";

            $class = $templater->processAttributeToRaw($attributes, 'class', ' %s', true);
            $xfInit = $templater->processAttributeToRaw($attributes, 'data-xf-init', '', true);

            $xfInitAttr = $xfInit ? " data-xf-init=\"$xfInit\"" : '';
            $unhandledAttrs = self::processUnhandledAttributes($attributes);

            $innerContent = '<img src="' . $iconUrl . '" '
                . ' alt="' . $node->title . '"'
                . ' class="brcni-node-icon ' . $typeClass . ' '.$class . '"'
                .$xfInitAttr.$unhandledAttrs
                . ' />';

            return $innerContent;
        });
    }

    protected static function processUnhandledAttributes(array $attributes)
    {
        $output = '';
        foreach ($attributes AS $name => $value)
        {
            if (is_array($value))
            {
                continue;
            }

            if ($value instanceof \XF\Phrase)
            {
                // strval will do escaping of the values or the whole phrase, so get the raw value and escape that here
                $value = $value->render('raw');
            }
            else
            {
                $value = strval($value);
            }

            if ($value !== '')
            {
                $output .= " $name=\"" . \XF::escapeString($value) . "\"";
            }
        }

        return $output;
    }
}