<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\RestBundle\Api\Helper\String;

/**
 * Class Index
 * @package Sso\RestBundle\Api\Helper\String
 */
class Index
{
    /**
     * @param string $string
     * @return array
     */
    public function validateJson($string)
    {
        $errorStorage = [];

        if (is_numeric($string)) {
            $errorStorage[] = 'no valid json string (int)';
        }

        json_decode($string);

        if (json_last_error() != JSON_ERROR_NONE) {
            $errorStorage[] = 'no valid json string';
        }

        return $errorStorage;
    }

    /**
     * @param string $xml
     * @return array
     */
    public function validateXML($xml)
    {
        $errorStorage = [];
        libxml_clear_errors();
        libxml_disable_entity_loader(true);
        libxml_use_internal_errors(true);

        $simpleXML = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_COMPACT);

        if (!$simpleXML) {
            $errors = libxml_get_errors();
            foreach ($errors as $error) {
                $errorStorage[] = $error->message;
            }
            libxml_clear_errors();
            libxml_disable_entity_loader(false);
        } else {
            libxml_clear_errors();
            libxml_disable_entity_loader(false);
        }

        return $errorStorage;
    }
}
