<?php

namespace Dipper\Foundation\Http\Middleware;

class HtmlSpecialchars extends TransformsRequest
{
    /**
     * The attributes that should not be trimmed.
     *
     * @var array
     */
    protected $except = [
        //
    ];

    /**
     * Transform the given value.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return mixed
     */
    protected function transform($key, $value)
    {
        if (in_array($key, $this->except, true)) {
            return $value;
        }

        return is_string($value) ? $this->htmlspecialchars($value) : $value;
    }

    /**
     * HTML 特殊字符转化
     */
    protected function htmlspecialchars($string, $flags = null)
    {
        if (is_array($string)) {
            foreach ($string as $key => $val) {
                $string[$key] = $this->htmlspecialchars($val, $flags);
            }
        } elseif (is_string($string)) {
            if ($flags === null) {
                $string = str_replace(['&', '"', '<', '>'], ['&amp;', '&quot;', '&lt;', '&gt;'], $string);
                if (strpos($string, '&amp;#') !== false) {
                    $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
                }
            } else {
                if (PHP_VERSION < '5.4.0') {
                    $string = htmlspecialchars($string, $flags);
                } else {
                    $string = htmlspecialchars($string, $flags, 'utf-8');
                }
            }
        }

        return $string;
    }
}
