<?php
/**
 * Copyright (C) Baluart.COM - All Rights Reserved
 *
 * @since 1.0
 * @author Balu
 * @copyright Copyright (c) 2015 - 2016 Baluart.COM
 * @license http://codecanyon.net/licenses/faq Envato marketplace licenses
 * @link http://easyforms.baluart.com/ Easy Forms
 */

namespace app\helpers;

use DOMDocument;

/**
 * Class Html
 * @package app\helpers
 * @extends \yii\helpers\Html
 */
class Html extends \yii\helpers\Html
{
    /**
     * Remove scripts tags from html code
     * @param $html
     * @return mixed
     */
    public static function removeScriptTags($html)
    {

        return preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);
    }

    /**
     * Return Allowed HTML5 Tags
     *
     * @return array
     */
    public static function allowedHtml5Tags()
    {
        return ["<source>","<audio>","<video>","<img>", "<del>","<ins>","<br>","<span>",
            "<u>","<b>","<i>","<sup>","<sub>", "<code>","<time>","<abbr>","<q>","<small>",
            "<strong>","<em>","<a>","<div>","<figcaption>","<figure>","<dd>","<dt>",
            "<dl>","<li>","<ul>","<ol>","<blockquote>","<pre>","<hr>","<p>","<address>"];
    }


    /**
     * Parse HTML code and find form fields
     * Return an array of field names
     *
     * @param $html Html code.
     * @return array List of Field Names
     */
    public static function getFields($html)
    {
        if (!empty($html)) {
            $dom = new DomDocument;
            // Hide Warnings
            libxml_use_internal_errors(true);
            $dom->validateOnParse = false;
            //load the html into the object
            $dom->loadHTML($html);
            //discard white space
            $dom->preserveWhiteSpace = false;
            // Get All dom elements
            $elements = $dom->getElementsByTagName('*');
            $fields = [];
            /* @var $element \DOMElement */
            foreach ($elements as $element) {
                // Only add form elements
                if (in_array($element->tagName, array("input", "textarea", "select"))) {
                    if ($element->hasAttribute('name')) {
                        $name = $element->getAttribute('name');
                        // Checkbox or Select List
                        if ($element->getAttribute('type') == "checkbox" || $element->tagName == "select") {
                            // Remove square brackets from name
                            $name = str_replace("[]", "", $name);
                        }
                        $fields[$name] = $name;
                    }
                }
            }
            return $fields;
        }
        return [];
    }
}
