<?php
/**
 * Extended ExpressionLanguage
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\TagManagerBundle\Util;

use Symfony\Component\ExpressionLanguage\ExpressionLanguage;

/**
 * Extended ExpressionLanguage
 *
 * ExpressionLanguage component with some usefull functions
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class ExtendedExpressionLanguage extends ExpressionLanguage
{

    /**
     * {@inheritdoc}
     */
    protected function registerFunctions()
    {
        parent::registerFunctions();
        $this->registerLowercase();
        $this->registerUppercase();
        $this->registerStart();
        $this->registerEnd();
        $this->registerHtml();
    }


    /**
     * Register lowercase() function
     */
    private function registerLowercase() {
        $this->register('lowercase', function ($str) {
            return sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str);
        }, function ($arguments, $str) {
            if (!is_string($str)) {
                return $str;
            }
            return strtolower($str);
        });
    }

    /**
     * Register uppercase() function
     */
    private function registerUppercase() {
        $this->register('uppercase', function ($str) {
            return sprintf('(is_string(%1$s) ? strtoupper(%1$s) : %1$s)', $str);
        }, function ($arguments, $str) {
            if (!is_string($str)) {
                return $str;
            }
            return strtoupper($str);
        });
    }

    /**
     * Register start() function
     */
    private function registerStart() {
        $this->register('start', function ($str, $length) {
            return sprintf('(is_string(%1$s) ? substr(%1$s, 0, %2$d) : %1$s)', $str, $length);
        }, function ($arguments, $str, $length) {
            if (!is_string($str)) {
                return $str;
            }
            return substr($str, 0, $length);
        });
    }

    /**
     * Register end() function
     */
    private function registerEnd() {
        $this->register('end', function ($str, $length) {
            return sprintf('(is_string(%1$s) ? substr(%1$s, %2$d) : %1$s)', $str, 0-$length);
        }, function ($arguments, $str, $length) {
            if (!is_string($str)) {
                return $str;
            }
            return substr($str, 0-$length);
        });
    }


    /**
     * Register html() function
     */
    private function registerHtml() {
        $this->register('html', function ($str) {
            return sprintf('(is_string(%1$s) ? htmlspecialchars(%1$s) : %1$s)', $str);
        }, function ($arguments, $str) {
            if (!is_string($str)) {
                return $str;
            }
            return htmlspecialchars($str);
        });
    }

}