<commit_before><?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         0.10.3
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Utility;

use Cake\Utility\Exception\XmlException;
use DOMDocument;
use DOMNode;
use DOMText;
use Exception;
use SimpleXMLElement;

/**
 * XML handling for CakePHP.
 *
 * The methods in these classes enable the datasources that use XML to work.
 */
class Xml
{

    /**
     * Initialize SimpleXMLElement or DOMDocument from a given XML string, file path, URL or array.
     *
     * ### Usage:
     *
     * Building XML from a string:
     *
     * ```
     * $xml = Xml::build('<example>text</example>');
     * ```
     *
     * Building XML from string (output DOMDocument):
     *
     * ```
     * $xml = Xml::build('<example>text</example>', ['return' => 'domdocument']);
     * ```
     *
     * Building XML from a file path:
     *
     * ```
     * $xml = Xml::build('/path/to/an/xml/file.xml');
     * ```
     *
     * Building XML from a remote URL:
     *
     * ```
     * use Cake\Http\Client;
     *
     * $http = new Client();
     * $response = $http->get('http://example.com/example.xml');
     * $xml = Xml::build($response->body());
     * ```
     *
     * Building from an array:
     *
     * ```
     *  $value = [
     *      'tags' => [
     *          'tag' => [
     *              [
     *                  'id' => '1',
     *                  'name' => 'defect'
     *              ],
     *              [
     *                  'id' => '2',
     *                  'name' => 'enhancement'
     *              ]
     *          ]
     *      ]
     *  ];
     * $xml = Xml::build($value);
     * ```
     *
     * When building XML from an array ensure that there is only one top level element.
     *
     * ### Options
     *
     * - `return` Can be 'simplexml' to return object of SimpleXMLElement or 'domdocument' to return DOMDocument.
     * - `loadEntities` Defaults to false. Set to true to enable loading of `<!ENTITY` definitions. This
     *   is disabled by default for security reasons.
     * - `readFile` Set to false to disable file reading. This is important to disable when
     *   putting user data into Xml::build(). If enabled local files will be read if they exist.
     *   Defaults to true for backwards compatibility reasons.
     * - `parseHuge` Enable the `LIBXML_PARSEHUGE` flag.
     *
     * If using array as input, you can pass `options` from Xml::fromArray.
     *
     * @param string|array $input XML string, a path to a file, a URL or an array
     * @param array $options The options to use
     * @return \SimpleXMLElement|\DOMDocument SimpleXMLElement or DOMDocument
     * @throws \Cake\Utility\Exception\XmlException
     */
    public static function build($input, array $options = [])
    {
        $defaults = [
            'return' => 'simplexml',
            'loadEntities' => false,
            'readFile' => true,
            'parseHuge' => false,
        ];
        $options += $defaults;

        if (is_array($input) || is_object($input)) {
            return static::fromArray($input, $options);
        }

        if (strpos($input, '<') !== false) {
            return static::_loadXml($input, $options);
        }

        if ($options['readFile'] && file_exists($input)) {
            return static::_loadXml(file_get_contents($input), $options);
        }

        if (!is_string($input)) {
            throw new XmlException('Invalid input.');
        }

        throw new XmlException('XML cannot be read.');
    }

    /**
     * Parse the input data and create either a SimpleXmlElement object or a DOMDocument.
     *
     * @param string $input The input to load.
     * @param array $options The options to use. See Xml::build()
     * @return \SimpleXMLElement|\DOMDocument
     * @throws \Cake\Utility\Exception\XmlException
     */
    protected static function _loadXml($input, $options)
    {
        $hasDisable = function_exists('libxml_disable_entity_loader');
        $internalErrors = libxml_use_internal_errors(true);
        if ($hasDisable && empty($options['loadEntities'])) {
            libxml_disable_entity_loader(true);
        }
        $flags = 0;
        if (!empty($options['parseHuge'])) {
            $flags |= LIBXML_PARSEHUGE;
        }
        try {
            if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
                $flags |= LIBXML_NOCDATA;
                $xml = new SimpleXMLElement($input, $flags);
            } else {
                $xml = new DOMDocument();
                $xml->loadXML($input, $flags);
            }

            return $xml;
        } catch (Exception $e) {
            throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e);
        } finally {
            if ($hasDisable && empty($options['loadEntities'])) {
                libxml_disable_entity_loader(false);
            }
            libxml_use_internal_errors($internalErrors);
        }
    }

    /**
     * Parse the input html string and create either a SimpleXmlElement object or a DOMDocument.
     *
     * @param string $input The input html string to load.
     * @param array $options The options to use. See Xml::build()
     * @return \SimpleXMLElement|\DOMDocument
     * @throws \Cake\Utility\Exception\XmlException
     */
    public static function loadHtml($input, $options)
    {
        $hasDisable = function_exists('libxml_disable_entity_loader');
        $internalErrors = libxml_use_internal_errors(true);
        if ($hasDisable && empty($options['loadEntities'])) {
            libxml_disable_entity_loader(true);
        }
        $flags = 0;
        if (!empty($options['parseHuge'])) {
            $flags |= LIBXML_PARSEHUGE;
        }
        try {
            $xml = new DOMDocument();
            $xml->loadHTML($input, $flags);

            if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
                $flags |= LIBXML_NOCDATA;
                                $xml = simplexml_import_dom($xml);
            }

            return $xml;
        } catch (Exception $e) {
            throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e);
        } finally {
            if ($hasDisable && empty($options['loadEntities'])) {
                libxml_disable_entity_loader(false);
            }
            libxml_use_internal_errors($internalErrors);
        }
    }

    /**
     * Transform an array into a SimpleXMLElement
     *
     * ### Options
     *
     * - `format` If create childs ('tags') or attributes ('attributes').
     * - `pretty` Returns formatted Xml when set to `true`. Defaults to `false`<commit_msg>Fixing style errors.<commit_after><?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         0.10.3
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Utility;

use Cake\Utility\Exception\XmlException;
use DOMDocument;
use DOMNode;
use DOMText;
use Exception;
use SimpleXMLElement;

/**
 * XML handling for CakePHP.
 *
 * The methods in these classes enable the datasources that use XML to work.
 */
class Xml
{

    /**
     * Initialize SimpleXMLElement or DOMDocument from a given XML string, file path, URL or array.
     *
     * ### Usage:
     *
     * Building XML from a string:
     *
     * ```
     * $xml = Xml::build('<example>text</example>');
     * ```
     *
     * Building XML from string (output DOMDocument):
     *
     * ```
     * $xml = Xml::build('<example>text</example>', ['return' => 'domdocument']);
     * ```
     *
     * Building XML from a file path:
     *
     * ```
     * $xml = Xml::build('/path/to/an/xml/file.xml');
     * ```
     *
     * Building XML from a remote URL:
     *
     * ```
     * use Cake\Http\Client;
     *
     * $http = new Client();
     * $response = $http->get('http://example.com/example.xml');
     * $xml = Xml::build($response->body());
     * ```
     *
     * Building from an array:
     *
     * ```
     *  $value = [
     *      'tags' => [
     *          'tag' => [
     *              [
     *                  'id' => '1',
     *                  'name' => 'defect'
     *              ],
     *              [
     *                  'id' => '2',
     *                  'name' => 'enhancement'
     *              ]
     *          ]
     *      ]
     *  ];
     * $xml = Xml::build($value);
     * ```
     *
     * When building XML from an array ensure that there is only one top level element.
     *
     * ### Options
     *
     * - `return` Can be 'simplexml' to return object of SimpleXMLElement or 'domdocument' to return DOMDocument.
     * - `loadEntities` Defaults to false. Set to true to enable loading of `<!ENTITY` definitions. This
     *   is disabled by default for security reasons.
     * - `readFile` Set to false to disable file reading. This is important to disable when
     *   putting user data into Xml::build(). If enabled local files will be read if they exist.
     *   Defaults to true for backwards compatibility reasons.
     * - `parseHuge` Enable the `LIBXML_PARSEHUGE` flag.
     *
     * If using array as input, you can pass `options` from Xml::fromArray.
     *
     * @param string|array $input XML string, a path to a file, a URL or an array
     * @param array $options The options to use
     * @return \SimpleXMLElement|\DOMDocument SimpleXMLElement or DOMDocument
     * @throws \Cake\Utility\Exception\XmlException
     */
    public static function build($input, array $options = [])
    {
        $defaults = [
            'return' => 'simplexml',
            'loadEntities' => false,
            'readFile' => true,
            'parseHuge' => false,
        ];
        $options += $defaults;

        if (is_array($input) || is_object($input)) {
            return static::fromArray($input, $options);
        }

        if (strpos($input, '<') !== false) {
            return static::_loadXml($input, $options);
        }

        if ($options['readFile'] && file_exists($input)) {
            return static::_loadXml(file_get_contents($input), $options);
        }

        if (!is_string($input)) {
            throw new XmlException('Invalid input.');
        }

        throw new XmlException('XML cannot be read.');
    }

    /**
     * Parse the input data and create either a SimpleXmlElement object or a DOMDocument.
     *
     * @param string $input The input to load.
     * @param array $options The options to use. See Xml::build()
     * @return \SimpleXMLElement|\DOMDocument
     * @throws \Cake\Utility\Exception\XmlException
     */
    protected static function _loadXml($input, $options)
    {
        $hasDisable = function_exists('libxml_disable_entity_loader');
        $internalErrors = libxml_use_internal_errors(true);
        if ($hasDisable && empty($options['loadEntities'])) {
            libxml_disable_entity_loader(true);
        }
        $flags = 0;
        if (!empty($options['parseHuge'])) {
            $flags |= LIBXML_PARSEHUGE;
        }
        try {
            if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
                $flags |= LIBXML_NOCDATA;
                $xml = new SimpleXMLElement($input, $flags);
            } else {
                $xml = new DOMDocument();
                $xml->loadXML($input, $flags);
            }

            return $xml;
        } catch (Exception $e) {
            throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e);
        } finally {
            if ($hasDisable && empty($options['loadEntities'])) {
                libxml_disable_entity_loader(false);
            }
            libxml_use_internal_errors($internalErrors);
        }
    }

    /**
     * Parse the input html string and create either a SimpleXmlElement object or a DOMDocument.
     *
     * @param string $input The input html string to load.
     * @param array $options The options to use. See Xml::build()
     * @return \SimpleXMLElement|\DOMDocument
     * @throws \Cake\Utility\Exception\XmlException
     */
    public static function loadHtml($input, $options)
    {
        $hasDisable = function_exists('libxml_disable_entity_loader');
        $internalErrors = libxml_use_internal_errors(true);
        if ($hasDisable && empty($options['loadEntities'])) {
            libxml_disable_entity_loader(true);
        }
        $flags = 0;
        if (!empty($options['parseHuge'])) {
            $flags |= LIBXML_PARSEHUGE;
        }
        try {
            $xml = new DOMDocument();
            $xml->loadHTML($input, $flags);

            if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
                $flags |= LIBXML_NOCDATA;
                $xml = simplexml_import_dom($xml);
            }

            return $xml;
        } catch (Exception $e) {
            throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e);
        } finally {
            if ($hasDisable && empty($options['loadEntities'])) {
                libxml_disable_entity_loader(false);
            }
            libxml_use_internal_errors($internalErrors);
        }
    }

    /**
     * Transform an array into a SimpleXMLElement
     *
     * ### Options
     *
     * - `format` If create childs ('tags') or attributes ('attributes').
     * - `pretty` Returns formatted Xml when set to `true`. Defaults to `false`
{'fraction_non_alphanumeric': 0.1315188032412217, 'fraction_numerical': 0.0011081099799155065, 'mean_word_length': 2.033613445378151, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 45, 'https://': 10, 'lorem ipsum': 0, 'www.': 0, 'xml': 68}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4697154', 'n_tokens_mistral': 4125, 'n_tokens_neox': 4046, 'n_words': 1097}