code:
<?php

/**
 * Hoa
 *
 *
 * @license
 *
 * New BSD License
 *
 * Copyright © 2007-2017, Hoa community. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Hoa nor the names of its contributors may be
 *       used to endorse or promote products derived from this software without
 *       specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

namespace Hoa\Exception\Test\Unit;

use Hoa\Exception\Idle as SUT;
use Hoa\Test;

/**
 * Class \Hoa\Exception\Test\Unit\Idle.
 *
 * Test suite of the idle exception.
 *
 * @copyright  Copyright © 2007-2017 Hoa community
 * @license    New BSD License
 */
class Idle extends Test\Unit\Suite
{
    public function case_is_a_real_exception()
    {
        $this
            ->when($result = new SUT('foo'))
            ->then
                ->object($result)
                    ->isInstanceOf('Exception');
    }

    public function case_get_backtrace()
    {
        $this
            ->given($exception = new SUT('foo'))
            ->when($result = $exception->getBacktrace())
            ->then
                ->array($result)
                    ->hasKey(0)
                ->array($result[0])
                    ->hasKey('file')
                    ->hasKey('line')
                    ->hasKey('function')
                    ->hasKey('class')
                    ->hasKey('type')
                    ->hasKey('args');
    }

    public function case_get_previous_throw()
    {
        $this
            ->given(
                $previous  = new SUT('previous'),
                $exception = new SUT('foo', 0, [], $previous)
            )
            ->when($result = $exception->getPreviousThrow())
            ->then
                ->object($result)
                    ->isIdenticalTo($previous);
    }

    public function case_get_arguments()
    {
        $this
            ->given($exception = new SUT('foo', 0, ['arg', 42, null]))
            ->when($result = $exception->getArguments())
            ->then
                ->array($result)
                    ->isEqualTo(['arg', 42, '(null)']);
    }

    public function case_get_arguments_from_a_string()
    {
        $this
            ->given($exception = new SUT('foo', 0, 'arg'))
            ->when($result = $exception->getArguments())
            ->then
                ->array($result)
                    ->isEqualTo(['arg']);
    }

    public function case_get_raw_message()
    {
        $this
            ->given(
                $message   = 'foo %s',
                $exception = new SUT($message)
            )
            ->when($result = $exception->getRawMessage())
            ->then
                ->string($result)
                    ->isEqualTo($message);
    }

    public function case_get_formatted_message()
    {
        $this
            ->given(
                $message   = 'foo %s',
                $exception = new SUT($message, 0, 'bar')
            )
            ->when($result = $exception->getFormattedMessage())
            ->then
                ->string($result)
                    ->isEqualTo($exception->getMessage())
                    ->isEqualTo('foo bar');
    }

    public function case_get_from_object()
    {
        $this
            ->given($exception = new SUT('foo'))
            ->when($result = $exception->getFrom())
            ->then
                ->string($result)
                    ->isEqualTo(__METHOD__ . '()');
    }

    public function case_raise()
    {
        $this
            ->given($exception = new SUT('foo'), $line = __LINE__)
            ->when($result = $exception->raise())
            ->then
                ->string($result)
                    ->isEqualTo(
                        __METHOD__ . '(): (0) foo' . "\n" .
                        'in ' . __FILE__ . ' at line ' . $line . '.'
                    );
    }

    public function case_raise_with_previous()
    {
        $this
            ->given(
                $previous  = new SUT('previous'), $previousLine = __LINE__,
                $exception = new SUT('foo', 0, [], $previous), $line = __LINE__
            )
            ->when($result = $exception->raise(true))
            ->then
                ->string($result)
                    ->isEqualTo(
                        __METHOD__ . '(): (0) foo' . "\n" .
                        'in ' . __FILE__ . ' at line ' . $line . '.' . "\n\n" .
                        '    ⬇' . "\n\n" .
                        'Nested exception (' . get_class($previous) . '):' . "\n" .
                        __METHOD__ . '(): (0) previous' . "\n" .
                        'in ' . __FILE__ . ' at line ' . $previousLine . '.'
                    );
    }

    public function case_uncaught()
    {
        $this
            ->given(
                $this->function->ob_get_level = 0,
                $exception = new SUT('foo'), $line = __LINE__
            )
            ->when($result = SUT::uncaught($exception))
            ->then
                ->variable($result)
                    ->isNull()
                ->output
                    ->isEqualTo(
                        'Uncaught exception (' . get_class($exception) . '):' . "\n" .
                        __METHOD__ . '(): (0) foo' . "\n" .
                        'in ' . __FILE__ . ' at line ' . $line . '.'
                    );
    }

    public function case_uncaught_not_Hoa()
    {
        $this
            ->exception(function () {
                SUT::uncaught(new \Exception('foo'));
            })
                ->isInstanceOf('Exception')
            ->output
                ->isEmpty();
    }

    public function case_to_string()
    {
        $this
            ->given($exception = new SUT('foo'))
            ->when($result = $exception->__toString())
            ->then
                ->string($result)
                    ->isEqualTo($exception->raise());
    }

    public function case_disable_uncaught_handler()
    {
        $this
            ->given(
                $this->function->restore_exception_handler = function () use (&$called) {
                    $called = true;

                    return null;
                }
            )
            ->when($result = SUT::enableUncaughtHandler(false))
            ->then
                ->variable($result)
                    ->isNull()
                ->boolean($called)
                    ->isTrue();
    }

    public function case_enable_uncaught_handler()
    {
        $self = $this;

        $this
            ->given(
                $this->function->set_exception_handler = function ($handler) use ($self, &$called) {
                    $called = true;

                    $self
                        ->object($handler)
                            ->isInstanceOf('Closure')
                        ->let($reflection = new \ReflectionObject($handler))
                        ->array($invokeParameters = $reflection->getMethod('__invoke')->getParameters())
                            ->hasSize(1)
                        ->string($invokeParameters[0]->getName())
                            ->isEqualTo('exception');

                    return null;
                }
            )
            ->when($result = SUT::enableUncaughtHandler())
            ->then
                ->variable($result)
                    ->isNull()
                ->boolean($called)
                    ->isTrue();
    }
}


hoa/exception

description: The Hoa\Exception library.

type: library

keywords: library exception

repo_name: andremichelle/gnu

license: mit


code:
vendor/
scratch.php
composer.lock
build/
.php_cs.cache


code:
<?php

$finder = PhpCsFixer\Finder::create()
    ->in(__DIR__)
;

return PhpCsFixer\Config::create()
    ->setRules(array(
        '@Symfony' => true,
        'concat_space' => array('spacing' => 'one'),
        'phpdoc_annotation_without_dot' => false,
    ))
    ->setFinder($finder)
;


code:
tools:
    php_mess_detector: true
    php_analyzer:
        config:
            parameter_reference_check: { enabled: false }
            checkstyle: { enabled: false, no_trailing_whitespace: true, naming: { enabled: true, local_variable: '^[a-z][a-zA-Z0-9]*$', abstract_class_name: ^Abstract|Factory$, utility_class_name: 'Utils?$', constant_name: '^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*$', property_name: '^[a-z][a-zA-Z0-9]*$', method_name: '^(?:[a-z]|__)[a-zA-Z0-9]*$', parameter_name: '^[a-z][a-zA-Z0-9]*$', interface_name: '^[A-Z][a-zA-Z0-9]*Interface$', type_name: '^[A-Z][a-zA-Z0-9]*$', exception_name: '^[A-Z][a-zA-Z0-9]*Exception$', isser_method_name: '^(?:is|has|should|may|supports)' } }
            unreachable_code: { enabled: false }
            check_access_control: { enabled: false }
            typo_checks: { enabled: false }
            check_variables: { enabled: false }
            check_calls: { enabled: true, too_many_arguments: true, missing_argument: true, argument_type_checks: lenient }
            suspicious_code: { enabled: false, overriding_parameter: false, overriding_closure_use: false, parameter_closure_use_conflict: false, parameter_multiple_times: false, non_existent_class_in_instanceof_check: false, non_existent_class_in_catch_clause: false, assignment_of_null_return: false, non_commented_switch_fallthrough: false, non_commented_empty_catch_block: false, overriding_private_members: false, use_statement_alias_conflict: false, precedence_in_condition_assignment: false }
            dead_assignments: { enabled: false }
            verify_php_doc_comments: { enabled: false, parameters: false, return: false, suggest_more_specific_types: false, ask_for_return_if_not_inferrable: false, ask_for_param_type_annotation: false }
            loops_must_use_braces: { enabled: false }
            check_usage_context: { enabled: true, foreach: { value_as_reference: true, traversable: true } }
            simplify_boolean_return: { enabled: false }
            phpunit_checks: { enabled: false }
            reflection_checks: { enabled: false }
            precedence_checks: { enabled: true, assignment_in_condition: true, comparison_of_bit_result: true }
            basic_semantic_checks: { enabled: false }
            unused_code: { enabled: false }
            deprecation_checks: { enabled: false }
            useless_function_calls: { enabled: false }
            metrics_lack_of_cohesion_methods: { enabled: false }
            metrics_coupling: { enabled: true, stable_code: { namespace_prefixes: {  }, classes: {  } } }
            doctrine_parameter_binding: { enabled: false }
            doctrine_entity_manager_injection: { enabled: false }
            symfony_request_injection: { enabled: false }
            doc_comment_fixes: { enabled: false }
            reflection_fixes: { enabled: false }
            use_statement_fixes: { enabled: true, remove_unused: true, preserve_multiple: false, preserve_blanklines: false, order_alphabetically: false }
    php_code_sniffer: true
    sensiolabs_security_checker: true
    php_cpd: true
    php_loc: true
    php_pdepend: true
    external_code_coverage: true
filter:
    paths:
        - src/*


code:
language: php
dist: trusty
sudo: false

matrix:
  include:
    - php: 5.3
      dist: precise
      env: COMPOSER_FLAGS="--prefer-lowest"
    - php: 5.4
    - php: 5.5
    - php: 5.6
      env: SCRUTINIZER=1
    - php: 7.0
      env: COMPOSER_FLAGS="--prefer-lowest"
    - php: 7.1
      env: CS_FIXER=1
    - php: 7.2
      env: BENCHMARK=1
    - php: hhvm
  fast_finish: true

cache:
  directories:
    - $HOME/.composer/cache

before_script:
  - composer self-update
  - composer update $COMPOSER_FLAGS --prefer-dist

script:
  - stty cols 120
  - if [ "$CS_FIXER" == 1 ]; then wget https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v2.13.1/php-cs-fixer.phar && php php-cs-fixer.phar fix --dry-run --diff; fi
  - mkdir -p build/logs
  - ./vendor/bin/phpunit --coverage-clover=coverage.xml

after_script:
  - if [ "$SCRUTINIZER" == 1 ]; then wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover coverage.xml; fi
  - if [ "$BENCHMARK" == 1 ]; then php test/benchmark/run.php 10; fi

notifications:
  irc: "irc.freenode.net#masterminds"


code:
Matt Butcher [technosophos] <technosophos@gmail.com> (lead)
Matt Farina  [mattfarina] <matt@mattfarina.com> (lead)
Asmir Mustafic [goetas] <goetas@lignano.it> (contributor)
Edward Z. Yang [ezyang] <ezyang@mit.edu> (contributor)
Geoffrey Sneddon [gsnedders] <geoffers@gmail.com> (contributor)
Kukhar Vasily [ngreduce] <ngreduce@gmail.com> (contributor)
Rune Christensen [MrElectronic] <mrelectronic@example.com> (contributor)
Mišo Belica [miso-belica] <miso-belica@example.com> (contributor)
Asmir Mustafic [goetas] <goetas@example.com> (contributor)
KITAITI Makoto [KitaitiMakoto] <KitaitiMakoto@example.com> (contributor)
Jacob Floyd [cognifloyd] <cognifloyd@gmail.com> (contributor)


code:
# HTML5-PHP

HTML5 is a standards-compliant HTML5 parser and writer written entirely in PHP.
It is stable and used in many production websites, and has
well over [five million downloads](https://packagist.org/packages/masterminds/html5).

HTML5 provides the following features.

- An HTML5 serializer
- Support for PHP namespaces
- Composer support
- Event-based (SAX-like) parser
- A DOM tree builder
- Interoperability with [QueryPath](https://github.com/technosophos/querypath)
- Runs on **PHP** 5.3.0 or newer and **HHVM** 3.2 or newer

[![Build Status](https://travis-ci.org/Masterminds/html5-php.png?branch=master)](https://travis-ci.org/Masterminds/html5-php)
[![Latest Stable Version](https://poser.pugx.org/masterminds/html5/v/stable.png)](https://packagist.org/packages/masterminds/html5)
[![Code Coverage](https://scrutinizer-ci.com/g/Masterminds/html5-php/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/Masterminds/html5-php/?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/Masterminds/html5-php/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/Masterminds/html5-php/?branch=master)
[![Stability: Sustained](https://masterminds.github.io/stability/sustained.svg)](https://masterminds.github.io/stability/sustained.html)

## Installation

Install HTML5-PHP using [composer](http://getcomposer.org/).

By adding the `masterminds/html5` dependency to your `composer.json` file:

```json
{
  "require" : {
    "masterminds/html5": "^2.0"
  },
}
```

By invoking require command via composer executable:

```bash
composer require masterminds/html5
```

## Basic Usage

HTML5-PHP has a high-level API and a low-level API.

Here is how you use the high-level `HTML5` library API:

```php
<?php
// Assuming you installed from Composer:
require "vendor/autoload.php";

use Masterminds\HTML5;

// An example HTML document:
$html = <<< 'HERE'
  <html>
  <head>
    <title>TEST</title>
  </head>
  <body id='foo'>
    <h1>Hello World</h1>
    <p>This is a test of the HTML5 parser.</p>
  </body>
  </html>
HERE;

// Parse the document. $dom is a DOMDocument.
$html5 = new HTML5();
$dom = $html5->loadHTML($html);

// Render it as HTML5:
print $html5->saveHTML($dom);

// Or save it to a file:
$html5->save($dom, 'out.html');
```

The `$dom` created by the parser is a full `DOMDocument` object. And the
`save()` and `saveHTML()` methods will take any DOMDocument.

### Options

It is possible to pass in an array of configuration options when loading
an HTML5 document.

```php
// An associative array of options
$options = array(
  'option_name' => 'option_value',
);

// Provide the options to the constructor
$html5 = new HTML5($options);

$dom = $html5->loadHTML($html);
```

The following options are supported:

* `encode_entities` (boolean): Indicates that the serializer should aggressively
  encode characters as entities. Without this, it only encodes the bare
  minimum.
* `disable_html_ns` (boolean): Prevents the parser from automatically
  assigning the HTML5 namespace to the DOM document. This is for
  non-namespace aware DOM tools.
* `target_document` (\DOMDocument): A DOM document that will be used as the
  destination for the parsed nodes.
* `implicit_namespaces` (array): An assoc array of namespaces that should be
  used by the parser. Name is tag prefix, value is NS URI.

## The Low-Level API

This library provides the following low-level APIs that you can use to
create more customized HTML5 tools:

- A SAX-like event-based parser that you can hook into for special kinds
of parsing.
- A flexible error-reporting mechanism that can be tuned to document
syntax checking.
- A DOM implementation that uses PHP's built-in DOM library.

The unit tests exercise each piece of the API, and every public function
is well-documented.

### Parser Design

The parser is designed as follows:

- The `Scanner` handles scanning on behalf of the parser.
- The `Tokenizer` requests data off of the scanner, parses it, clasifies
it, and sends it to an `EventHandler`. It is a *recursive descent parser.*
- The `EventHandler` receives notifications and data for each specific
semantic event that occurs during tokenization.
- The `DOMBuilder` is an `EventHandler` that listens for tokenizing
events and builds a document tree (`DOMDocument`) based on the events.

### Serializer Design

The serializer takes a data structure (the `DOMDocument`) and transforms
it into a character representation -- an HTML5 document.

The serializer is broken into three parts:

- The `OutputRules` contain the rules to turn DOM elements into strings. The
rules are an implementation of the interface `RulesInterface` allowing for
different rule sets to be used.
- The `Traverser`, which is a special-purpose tree walker. It visits
each node node in the tree and uses the `OutputRules` to transform the node
into a string.
- `HTML5` manages the `Traverser` and stores the resultant data
in the correct place.

The serializer (`save()`, `saveHTML()`) follows the
[section 8.9 of the HTML 5.0 spec](http://www.w3.org/TR/2012/CR-html5-20121217/syntax.html#serializing-html-fragments).
So tags are serialized according to these rules:

- A tag with children: <foo>CHILDREN</foo>
- A tag that cannot have content: <foo> (no closing tag)
- A tag that could have content, but doesn't: <foo></foo>

## Known Issues (Or, Things We Designed Against the Spec)

Please check the issue queue for a full list, but the following are
issues known issues that are not presently on the roadmap:

- Namespaces: HTML5 only [supports a selected list of namespaces](http://www.w3.org/TR/html5/infrastructure.html#namespaces)
  and they do not operate in the same way as XML namespaces. A `:` has no special
  meaning.
  By default the parser does not support XML style namespaces via `:`;
  to enable the XML namespaces see the  [XML Namespaces section](#xml-namespaces)
- Scripts: This parser does not contain a JavaScript or a CSS
  interpreter. While one may be supplied, not all features will be
  supported.
- Rentrance: The current parser is not re-entrant. (Thus you can't pause
  the parser to modify the HTML string mid-parse.)
- Validation: The current tree builder is **not** a validating parser.
  While it will correct some HTML, it does not check that the HTML
  conforms to the standard. (Should you wish, you can build a validating
  parser by extending DOMTree or building your own EventHandler
  implementation.)
  * There is limited support for insertion modes.
  * Some autocorrection is done automatically.
  * Per the spec, many legacy tags are admitted and correctly handled,
    even though they are technically not part of HTML5.
- Attribute names and values: Due to the implementation details of the
  PHP implementation of DOM, attribute names that do not follow the
  XML 1.0 standard are not inserted into the DOM. (Effectively, they
  are ignored.) If you've got a clever fix for this, jump in!
- Processor Instructions: The HTML5 spec does not allow processor
  instructions. We do. Since this is a server-side library, we think
  this is useful. And that means, dear reader, that in some cases you
  can parse the HTML from a mixed PHP/HTML document. This, however,
  is an incidental feature, not a core feature.
- HTML manifests: Unsupported.
- PLAINTEXT: Unsupported.
- Adoption Agency Algorithm: Not yet implemented. (8.2.5.4.7)

## XML Namespaces

To use XML style namespaces you have to configure well the main `HTML5` instance.

```php
use Masterminds\HTML5;
$html = new HTML5(array(
    "xmlNamespaces" => true
));

$dom = $html->loadHTML('<t:tag xmlns:t="http://www.example.com"/>');

$dom->documentElement->namespaceURI; // http://www.example.com

```

You can also add some default prefixes that will not require the namespace declaration,
but its elements will be namespaced.

```php
use Masterminds\HTML5;
$html = new HTML5(array(
    "implicitNamespaces"=>array(
        "t"=>"http://www.example.com"
    )
));

$dom = $html->loadHTML('<t:tag/>');

$dom->documentElement->namespaceURI; // http://www.example.com

```

## Thanks to...

The dedicated (and patient) contributors of patches small and large,
who have already made this library better.See the CREDITS file for
a list of contributors.

We owe a huge debt of gratitude to the original authors of html5lib.

While not much of the original parser remains, we learned a lot from
reading the html5lib library. And some pieces remain here. In
particular, much of the UTF-8 and Unicode handling is derived from the
html5lib project.

## License

This software is released under the MIT license. The original html5lib
library was also released under the MIT license.

See LICENSE.txt

Certain files contain copyright assertions by specific individuals
involved with html5lib. Those have been retained where appropriate.


code:
# Release Notes

2.6.0 (2019-03-10)

- #163: Allow to pass a charset to the Scanner

2.5.0 (2018-12-27)

- #162, #161, #155, #154, #153, #151: big performance improvements
- #156: fixed typos
- #160: adopt and enforce code style
- #159: remove deprecated php unit base test case
- #150: backport changes from old master branch

2.4.0 (2018-11-17)

- #148: Improve performance by moving sequence matching
- #147: Improve the Tokenizer performance
- #146: Improve performance by relying on a native string instead of InputStream
- #144: Add DOM extension in composer.json
- #145: Add more extensions on composer.json, improve phpdocs and remove dead code
- #143: Remove experimental comment

2.3.1 (2018-10-18)

- #121: Audio is not a block tag (fixed by #141)
- #136: Handle illegal self-closing according to spec (fixed by #137)
- #141: Minor fixes in the README

2.3.0 (2017-09-04)

- #129: image within inline svg breaks system (fixed by #133)
- #131: ² does not work (fixed by #132)
- #134: Improve tokenizer performance by 20% (alternative version of #130 thanks to @MichaelHeerklotz)
- #135: Raw & in attributes

2.2.2 (2016-09-22)

- #116: In XML mode, tags are case sensitive
- #115: Fix PHP Notice in OutputRules
- #112: fix parsing of options of an optgroup
- #111: Adding test for the address tag

2.2.1 (2016-05-10)

- #109: Fixed issue where address tag could be written without closing tag (thanks sylus)

2.2.0 (2016-04-11)

- #105: Enable composer cache (for CI/CD)
- #100: Use mb_substitute_character inset of ini_set for environments where ini_set is disable (e.g., shared hosting)
- #98: Allow link, meta, style tags in noscript tags
- #96: Fixed xml:href on svgs that use the "use" breaking
- #94: Counting UTF8 characters performance improvement
- #93: Use newer version of coveralls package
- #90: Remove duplicate test
- #87: Allow multiple root nodes

2.1.2 (2015-06-07)
- #82: Support for PHP7
- #84: Improved boolean attribute handling

2.1.1 (2015-03-23)
- #78: Fixes bug where unmatched entity like string drops everything after &.

2.1.0 (2015-02-01)
- #74: Added `disable_html_ns` and `target_doc` dom parsing options
- Unified option names
- #73: Fixed alphabet, ß now can be detected
- #75 and #76: Allow whitespace in RCDATA tags
- #77: Fixed parsing blunder for json embeds
- #72: Add options to HTML methods

2.0.2 (2014-12-17)
- #50: empty document handling
- #63: tags with strange capitalization
- #65: dashes and underscores as allowed characters in tag names
- #68: Fixed issue with non-inline elements inside inline containers

2.0.1 (2014-09-23)
- #59: Fixed issue parsing some fragments.
- #56: Incorrectly saw 0 as empty string
- Sami as new documentation generator

2.0.0 (2014-07-28)
- #53: Improved boolean attributes handling
- #52: Facebook HHVM compatibility
- #48: Adopted PSR-2 as coding standard
- #47: Moved everything to Masterminds namespace
- #45: Added custom namespaces
- #44: Added support to XML-style namespaces
- #37: Refactored HTML5 class removing static methods

1.0.5 (2014-06-10)
- #38: Set the dev-master branch as the 1.0.x branch for composer (goetas)
- #34: Tests use PSR-4 for autoloading. (goetas)
- #40, #41: Fix entity handling in RCDATA sections. (KitaitiMakoto)
- #32: Fixed issue where wharacter references were being incorrectly encoded in style tags.

1.0.4 (2014-04-29)
- #30/#31 Don't throw an exception for invalid tag names.

1.0.3 (2014-02-28)
- #23 and #29: Ignore attributes with illegal chars in name for the PHP DOM.

1.0.2 (2014-02-12)
- #23: Handle missing tag close in attribute list.
- #25: Fixed text escaping in the serializer (HTML% 8.3).
- #27: Fixed tests on Windows: changed "\n" -> PHP_EOL.
- #28: Fixed infinite loop for char "&" in unquoted attribute in parser.
- #26: Updated tag name case handling to deal with uppercase usage.
- #24: Newlines and tabs are allowed inside quoted attributes (HTML5 8.2.4).
- Fixed Travis CI testing.

1.0.1 (2013-11-07)
- CDATA encoding is improved. (Non-standard; Issue #19)
- Some parser rules were not returning the new current element. (Issue #20)
- Added, to the README, details on code test coverage and to packagist version.
- Fixed processor instructions.
- Improved test coverage and documentation coverage.

1.0.0 (2013-10-02)
- Initial release.


code:
From 1.x to 2.x
=================

- All classes uses `Masterminds` namespace.
- All public static methods has been removed from `HTML5` class and the general API to access the HTML5 functionalities has changed.

    Before:

        $dom = \HTML5::loadHTML('<html>....');
        \HTML5::saveHTML($dom);

    After:

        use Masterminds\HTML5;

        $html5 = new HTML5();

        $dom = $html5->loadHTML('<html>....');
        echo $html5->saveHTML($dom);


code:
<?php
/**
 * Fetch the entities.json file and convert to PHP datastructure.
 */

// The URL to the official entities JSON file.
$ENTITIES_URL = 'http://www.w3.org/TR/2012/CR-html5-20121217/entities.json';

$payload = file_get_contents($ENTITIES_URL);
$json = json_decode($payload);

$table = array();
foreach ($json as $name => $obj) {
    $sname = substr($name, 1, -1);
    $table[$sname] = $obj->characters;
}

echo '<?php
namespace Masterminds\\HTML5;
/** Entity lookup tables. This class is automatically generated. */
class Entities {
  public static $byName = ';
var_export($table);
echo ';
}' . PHP_EOL;
//print serialize($table);


description: An HTML5 parser and serializer.

license: MIT

keywords: xml html html5 dom parser serializer querypath

Masterminds\: src


code:
<?php

require 'vendor/autoload.php';
use Masterminds\HTML5;

$html = <<< 'HERE'

  <title>TEST</title>

Hello World

This is a test of the HTML5 parser.

  & Nobody nowhere.

  <test xmlns:foo="http://example.com/foo">TEST</test>
  <![CDATA[Because we can.]]>
  ©

HERE;

$html5 = new HTML5();
$dom = $html5->loadHTML($html);

echo "Converting to HTML 5\n";

$html5->save($dom, fopen('php://stdin', 'w'));


code:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="PHPUnit">
          <directory>test/HTML5/</directory>
        </testsuite>
    </testsuites>
    <filter>
        <blacklist>
            <file>systemlib.phpreflection_hni</file>
            <file>src/HTML5/Parser/InputStream.php</file>
            <file>src/HTML5/Serializer/RulesInterface.php</file>
            <file>src/HTML5/Entities.php</file>
            <file>src/HTML5/Serializer/HTML5Entities.php</file>
        </blacklist>
    </filter>
</phpunit>


code:
<?php

use Sami\Sami;

return new Sami(__DIR__ . '/src', array(
    'title' => 'HTML5-PHP API',
    'build_dir' => __DIR__ . '/build/apidoc',
    'cache_dir' => __DIR__ . '/build/sami-cache',
    'default_opened_level' => 1,
));


code:
<?php

namespace Masterminds;

use Masterminds\HTML5\Parser\DOMTreeBuilder;
use Masterminds\HTML5\Parser\Scanner;
use Masterminds\HTML5\Parser\Tokenizer;
use Masterminds\HTML5\Serializer\OutputRules;
use Masterminds\HTML5\Serializer\Traverser;

/**
 * This class offers convenience methods for parsing and serializing HTML5.
 * It is roughly designed to mirror the \DOMDocument native class.
 */
class HTML5
{
    /**
     * Global options for the parser and serializer.
     *
     * @var array
     */
    private $defaultOptions = array(
        // Whether the serializer should aggressively encode all characters as entities.
        'encode_entities' => false,

        // Prevents the parser from automatically assigning the HTML5 namespace to the DOM document.
        'disable_html_ns' => false,
    );

    protected $errors = array();

    public function __construct(array $defaultOptions = array())
    {
        $this->defaultOptions = array_merge($this->defaultOptions, $defaultOptions);
    }

    /**
     * Get the current default options.
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->defaultOptions;
    }

    /**
     * Load and parse an HTML file.
     *
     * This will apply the HTML5 parser, which is tolerant of many
     * varieties of HTML, including XHTML 1, HTML 4, and well-formed HTML
     * 3. Note that in these cases, not all of the old data will be
     * preserved. For example, XHTML's XML declaration will be removed.
     *
     * The rules governing parsing are set out in the HTML 5 spec.
     *
     * @param string|resource $file    The path to the file to parse. If this is a resource, it is
     *                                 assumed to be an open stream whose pointer is set to the first
     *                                 byte of input.
     * @param array           $options Configuration options when parsing the HTML.
     *
     * @return \DOMDocument A DOM document. These object type is defined by the libxml
     *                      library, and should have been included with your version of PHP.
     */
    public function load($file, array $options = array())
    {
        // Handle the case where file is a resource.
        if (is_resource($file)) {
            return $this->parse(stream_get_contents($file), $options);
        }

        return $this->parse(file_get_contents($file), $options);
    }

    /**
     * Parse a HTML Document from a string.
     *
     * Take a string of HTML 5 (or earlier) and parse it into a
     * DOMDocument.
     *
     * @param string $string  A html5 document as a string.
     * @param array  $options Configuration options when parsing the HTML.
     *
     * @return \DOMDocument A DOM document. DOM is part of libxml, which is included with
     *                      almost all distribtions of PHP.
     */
    public function loadHTML($string, array $options = array())
    {
        return $this->parse($string, $options);
    }

    /**
     * Convenience function to load an HTML file.
     *
     * This is here to provide backwards compatibility with the
     * PHP DOM implementation. It simply calls load().
     *
     * @param string $file    The path to the file to parse. If this is a resource, it is
     *                        assumed to be an open stream whose pointer is set to the first
     *                        byte of input.
     * @param array  $options Configuration options when parsing the HTML.
     *
     * @return \DOMDocument A DOM document. These object type is defined by the libxml
     *                      library, and should have been included with your version of PHP.
     */
    public function loadHTMLFile($file, array $options = array())
    {
        return $this->load($file, $options);
    }

    /**
     * Parse a HTML fragment from a string.
     *
     * @param string $string  the HTML5 fragment as a string
     * @param array  $options Configuration options when parsing the HTML
     *
     * @return \DOMDocumentFragment A DOM fragment. The DOM is part of libxml, which is included with
     *                              almost all distributions of PHP.
     */
    public function loadHTMLFragment($string, array $options = array())
    {
        return $this->parseFragment($string, $options);
    }

    /**
     * Return all errors encountered into parsing phase.
     *
     * @return array
     */
    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * Return true it some errors were encountered into parsing phase.
     *
     * @return bool
     */
    public function hasErrors()
    {
        return count($this->errors) > 0;
    }

    /**
     * Parse an input string.
     *
     * @param string $input
     * @param array  $options
     *
     * @return \DOMDocument
     */
    public function parse($input, array $options = array())
    {
        $this->errors = array();
        $options = array_merge($this->defaultOptions, $options);
        $events = new DOMTreeBuilder(false, $options);
        $scanner = new Scanner($input, !empty($options['encoding']) ? $options['encoding'] : 'UTF-8');
        $parser = new Tokenizer($scanner, $events, !empty($options['xmlNamespaces']) ? Tokenizer::CONFORMANT_XML : Tokenizer::CONFORMANT_HTML);

        $parser->parse();
        $this->errors = $events->getErrors();

        return $events->document();
    }

    /**
     * Parse an input stream where the stream is a fragment.
     *
     * Lower-level loading function. This requires an input stream instead
     * of a string, file, or resource.
     *
     * @param string $input   The input data to parse in the form of a string.
     * @param array  $options An array of options.
     *
     * @return \DOMDocumentFragment
     */
    public function parseFragment($input, array $options = array())
    {
        $options = array_merge($this->defaultOptions, $options);
        $events = new DOMTreeBuilder(true, $options);
        $scanner = new Scanner($input, !empty($options['encoding']) ? $options['encoding'] : 'UTF-8');
        $parser = new Tokenizer($scanner, $events, !empty($options['xmlNamespaces']) ? Tokenizer::CONFORMANT_XML : Tokenizer::CONFORMANT_HTML);

        $parser->parse();
        $this->errors = $events->getErrors();

        return $events->fragment();
    }

    /**
     * Save a DOM into a given file as HTML5.
     *
     * @param mixed           $dom     The DOM to be serialized.
     * @param string|resource $file    The filename to be written or resource to write to.
     * @param array           $options Configuration options when serializing the DOM. These include:
     *                                 - encode_entities: Text written to the output is escaped by default and not all
     *                                 entities are encoded. If this is set to true all entities will be encoded.
     *                                 Defaults to false.
     */
    public function save($dom, $file, $options = array())
    {
        $close = true;
        if (is_resource($file)) {
            $stream = $file;
            $close = false;
        } else {
            $stream = fopen($file, 'wb');
        }
        $options = array_merge($this->defaultOptions, $options);
        $rules = new OutputRules($stream, $options);
        $trav = new Traverser($dom, $stream, $rules, $options);

        $trav->walk();

        if ($close) {
            fclose($stream);
        }
    }

    /**
     * Convert a DOM into an HTML5 string.
     *
     * @param mixed $dom     The DOM to be serialized.
     * @param array $options Configuration options when serializing the DOM. These include:
     *                       - encode_entities: Text written to the output is escaped by default and not all
     *                       entities are encoded. If this is set to true all entities will be encoded.
     *                       Defaults to false.
     *
     * @return string A HTML5 documented generated from the DOM.
     */
    public function saveHTML($dom, $options = array())
    {
        $stream = fopen('php://temp', 'wb');
        $this->save($dom, $stream, array_merge($this->defaultOptions, $options));

        return stream_get_contents($stream, -1, 0);
    }
}


code:
<?php
/**
 * Provide general element functions.
 */

namespace Masterminds\HTML5;

/**
 * This class provides general information about HTML5 elements,
 * including syntactic and semantic issues.
 * Parsers and serializers can
 * use this class as a reference point for information about the rules
 * of various HTML5 elements.
 *
 * @todo consider using a bitmask table lookup. There is enough overlap in
 *       naming that this could significantly shrink the size and maybe make it
 *       faster. See the Go teams implementation at https://code.google.com/p/go/source/browse/html/atom.
 */
class Elements
{
    /**
     * Indicates an element is described in the specification.
     */
    const KNOWN_ELEMENT = 1;

    // From section 8.1.2: "script", "style"
    // From 8.2.5.4.7 ("in body" insertion mode): "noembed"
    // From 8.4 "style", "xmp", "iframe", "noembed", "noframes"
    /**
     * Indicates the contained text should be processed as raw text.
     */
    const TEXT_RAW = 2;

    // From section 8.1.2: "textarea", "title"
    /**
     * Indicates the contained text should be processed as RCDATA.
     */
    const TEXT_RCDATA = 4;

    /**
     * Indicates the tag cannot have content.
     */
    const VOID_TAG = 8;

    // "address", "article", "aside", "blockquote", "center", "details", "dialog", "dir", "div", "dl",
    // "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu",
    // "nav", "ol", "p", "section", "summary", "ul"
    // "h1", "h2", "h3", "h4", "h5", "h6"
    // "pre", "listing"
    // "form"
    // "plaintext"
    /**
     * Indicates that if a previous event is for a P tag, that element
     * should be considered closed.
     */
    const AUTOCLOSE_P = 16;

    /**
     * Indicates that the text inside is plaintext (pre).
     */
    const TEXT_PLAINTEXT = 32;

    // See https://developer.mozilla.org/en-US/docs/HTML/Block-level_elements
    /**
     * Indicates that the tag is a block.
     */
    const BLOCK_TAG = 64;

    /**
     * Indicates that the tag allows only inline elements as child nodes.
     */
    const BLOCK_ONLY_INLINE = 128;

    /**
     * The HTML5 elements as defined in http://dev.w3.org/html5/markup/elements.html.
     *
     * @var array
     */
    public static $html5 = array(
        'a' => 1,
        'abbr' => 1,
        'address' => 65, // NORMAL | BLOCK_TAG
        'area' => 9, // NORMAL | VOID_TAG
        'article' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'aside' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'audio' => 1, // NORMAL
        'b' => 1,
        'base' => 9, // NORMAL | VOID_TAG
        'bdi' => 1,
        'bdo' => 1,
        'blockquote' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'body' => 1,
        'br' => 9, // NORMAL | VOID_TAG
        'button' => 1,
        'canvas' => 65, // NORMAL | BLOCK_TAG
        'caption' => 1,
        'cite' => 1,
        'code' => 1,
        'col' => 9, // NORMAL | VOID_TAG
        'colgroup' => 1,
        'command' => 9, // NORMAL | VOID_TAG
                        // "data" => 1, // This is highly experimental and only part of the whatwg spec (not w3c). See https://developer.mozilla.org/en-US/docs/HTML/Element/data
        'datalist' => 1,
        'dd' => 65, // NORMAL | BLOCK_TAG
        'del' => 1,
        'details' => 17, // NORMAL | AUTOCLOSE_P,
        'dfn' => 1,
        'dialog' => 17, // NORMAL | AUTOCLOSE_P,
        'div' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'dl' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'dt' => 1,
        'em' => 1,
        'embed' => 9, // NORMAL | VOID_TAG
        'fieldset' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'figcaption' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'figure' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'footer' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'form' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'h1' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'h2' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'h3' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'h4' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'h5' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'h6' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'head' => 1,
        'header' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'hgroup' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'hr' => 73, // NORMAL | VOID_TAG
        'html' => 1,
        'i' => 1,
        'iframe' => 3, // NORMAL | TEXT_RAW
        'img' => 9, // NORMAL | VOID_TAG
        'input' => 9, // NORMAL | VOID_TAG
        'kbd' => 1,
        'ins' => 1,
        'keygen' => 9, // NORMAL | VOID_TAG
        'label' => 1,
        'legend' => 1,
        'li' => 1,
        'link' => 9, // NORMAL | VOID_TAG
        'map' => 1,
        'mark' => 1,
        'menu' => 17, // NORMAL | AUTOCLOSE_P,
        'meta' => 9, // NORMAL | VOID_TAG
        'meter' => 1,
        'nav' => 17, // NORMAL | AUTOCLOSE_P,
        'noscript' => 65, // NORMAL | BLOCK_TAG
        'object' => 1,
        'ol' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'optgroup' => 1,
        'option' => 1,
        'output' => 65, // NORMAL | BLOCK_TAG
        'p' => 209, // NORMAL | AUTOCLOSE_P | BLOCK_TAG | BLOCK_ONLY_INLINE
        'param' => 9, // NORMAL | VOID_TAG
        'pre' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'progress' => 1,
        'q' => 1,
        'rp' => 1,
        'rt' => 1,
        'ruby' => 1,
        's' => 1,
        'samp' => 1,
        'script' => 3, // NORMAL | TEXT_RAW
        'section' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'select' => 1,
        'small' => 1,
        'source' => 9, // NORMAL | VOID_TAG
        'span' => 1,
        'strong' => 1,
        'style' => 3, // NORMAL | TEXT_RAW
        'sub' => 1,
        'summary' => 17, // NORMAL | AUTOCLOSE_P,
        'sup' => 1,
        'table' => 65, // NORMAL | BLOCK_TAG
        'tbody' => 1,
        'td' => 1,
        'textarea' => 5, // NORMAL | TEXT_RCDATA
        'tfoot' => 65, // NORMAL | BLOCK_TAG
        'th' => 1,
        'thead' => 1,
        'time' => 1,
        'title' => 5, // NORMAL | TEXT_RCDATA
        'tr' => 1,
        'track' => 9, // NORMAL | VOID_TAG
        'u' => 1,
        'ul' => 81, // NORMAL | AUTOCLOSE_P | BLOCK_TAG
        'var' => 1,
        'video' => 65, // NORMAL | BLOCK_TAG
        'wbr' => 9, // NORMAL | VOID_TAG

        // Legacy?
        'basefont' => 8, // VOID_TAG
        'bgsound' => 8, // VOID_TAG
        'noframes' => 2, // RAW_TEXT
        'frame' => 9, // NORMAL | VOID_TAG
        'frameset' => 1,
        'center' => 16,
        'dir' => 16,
        'listing' => 16, // AUTOCLOSE_P
        'plaintext' => 48, // AUTOCLOSE_P | TEXT_PLAINTEXT
        'applet' => 0,
        'marquee' => 0,
        'isindex' => 8, // VOID_TAG
        'xmp' => 20, // AUTOCLOSE_P | VOID_TAG | RAW_TEXT
        'noembed' => 2, // RAW_TEXT
        );

    /**
     * The MathML elements.
     * See http://www.w3.org/wiki/MathML/Elements.
     *
     * In our case we are only concerned with presentation MathML and not content
     * MathML. There is a nice list of this subset at https://developer.mozilla.org/en-US/docs/MathML/Element.
     *
     * @var array
     */
    public static $mathml = array(
        'maction' => 1,
        'maligngroup' => 1,
        'malignmark' => 1,
        'math' => 1,
        'menclose' => 1,
        'merror' => 1,
        'mfenced' => 1,
        'mfrac' => 1,
        'mglyph' => 1,
        'mi' => 1,
        'mlabeledtr' => 1,
        'mlongdiv' => 1,
        'mmultiscripts' => 1,
        'mn' => 1,
        'mo' => 1,
        'mover' => 1,
        'mpadded' => 1,
        'mphantom' => 1,
        'mroot' => 1,
        'mrow' => 1,
        'ms' => 1,
        'mscarries' => 1,
        'mscarry' => 1,
        'msgroup' => 1,
        'msline' => 1,
        'mspace' => 1,
        'msqrt' => 1,
        'msrow' => 1,
        'mstack' => 1,
        'mstyle' => 1,
        'msub' => 1,
        'msup' => 1,
        'msubsup' => 1,
        'mtable' => 1,
        'mtd' => 1,
        'mtext' => 1,
        'mtr' => 1,
        'munder' => 1,
        'munderover' => 1,
    );

    /**
     * The svg elements.
     *
     * The Mozilla documentation has a good list at https://developer.mozilla.org/en-US/docs/SVG/Element.
     * The w3c list appears to be lacking in some areas like filter effect elements.
     * That list can be found at http://www.w3.org/wiki/SVG/Elements.
     *
     * Note, FireFox appears to do a better job rendering filter effects than chrome.
     * While they are in the spec I'm not sure how widely implemented they are.
     *
     * @var array
     */
    public static $svg = array(
        'a' => 1,
        'altGlyph' => 1,
        'altGlyphDef' => 1,
        'altGlyphItem' => 1,
        'animate' => 1,
        'animateColor' => 1,
        'animateMotion' => 1,
        'animateTransform' => 1,
        'circle' => 1,
        'clipPath' => 1,
        'color-profile' => 1,
        'cursor' => 1,
        'defs' => 1,
        'desc' => 1,
        'ellipse' => 1,
        'feBlend' => 1,
        'feColorMatrix' => 1,
        'feComponentTransfer' => 1,
        'feComposite' => 1,
        'feConvolveMatrix' => 1,
        'feDiffuseLighting' => 1,
        'feDisplacementMap' => 1,
        'feDistantLight' => 1,
        'feFlood' => 1,
        'feFuncA' => 1,
        'feFuncB' => 1,
        'feFuncG' => 1,
        'feFuncR' => 1,
        'feGaussianBlur' => 1,
        'feImage' => 1,
        'feMerge' => 1,
        'feMergeNode' => 1,
        'feMorphology' => 1,
        'feOffset' => 1,
        'fePointLight' => 1,
        'feSpecularLighting' => 1,
        'feSpotLight' => 1,
        'feTile' => 1,
        'feTurbulence' => 1,
        'filter' => 1,
        'font' => 1,
        'font-face' => 1,
        'font-face-format' => 1,
        'font-face-name' => 1,
        'font-face-src' => 1,
        'font-face-uri' => 1,
        'foreignObject' => 1,
        'g' => 1,
        'glyph' => 1,
        'glyphRef' => 1,
        'hkern' => 1,
        'image' => 1,
        'line' => 1,
        'linearGradient' => 1,
        'marker' => 1,
        'mask' => 1,
        'metadata' => 1,
        'missing-glyph' => 1,
        'mpath' => 1,
        'path' => 1,
        'pattern' => 1,
        'polygon' => 1,
        'polyline' => 1,
        'radialGradient' => 1,
        'rect' => 1,
        'script' => 3, // NORMAL | RAW_TEXT
        'set' => 1,
        'stop' => 1,
        'style' => 3, // NORMAL | RAW_TEXT
        'svg' => 1,
        'switch' => 1,
        'symbol' => 1,
        'text' => 1,
        'textPath' => 1,
        'title' => 1,
        'tref' => 1,
        'tspan' => 1,
        'use' => 1,
        'view' => 1,
        'vkern' => 1,
    );

    /**
     * Some attributes in SVG are case sensitive.
     *
     * This map contains key/value pairs with the key as the lowercase attribute
     * name and the value with the correct casing.
     */
    public static $svgCaseSensitiveAttributeMap = array(
        'attributename' => 'attributeName',
        'attributetype' => 'attributeType',
        'basefrequency' => 'baseFrequency',
        'baseprofile' => 'baseProfile',
        'calcmode' => 'calcMode',
        'clippathunits' => 'clipPathUnits',
        'contentscripttype' => 'contentScriptType',
        'contentstyletype' => 'contentStyleType',
        'diffuseconstant' => 'diffuseConstant',
        'edgemode' => 'edgeMode',
        'externalresourcesrequired' => 'externalResourcesRequired',
        'filterres' => 'filterRes',
        'filterunits' => 'filterUnits',
        'glyphref' => 'glyphRef',
        'gradienttransform' => 'gradientTransform',
        'gradientunits' => 'gradientUnits',
        'kernelmatrix' => 'kernelMatrix',
        'kernelunitlength' => 'kernelUnitLength',
        'keypoints' => 'keyPoints',
        'keysplines' => 'keySplines',
        'keytimes' => 'keyTimes',
        'lengthadjust' => 'lengthAdjust',
        'limitingconeangle' => 'limitingConeAngle',
        'markerheight' => 'markerHeight',
        'markerunits' => 'markerUnits',
        'markerwidth' => 'markerWidth',
        'maskcontentunits' => 'maskContentUnits',
        'maskunits' => 'maskUnits',
        'numoctaves' => 'numOctaves',
        'pathlength' => 'pathLength',
        'patterncontentunits' => 'patternContentUnits',
        'patterntransform' => 'patternTransform',
        'patternunits' => 'patternUnits',
        'pointsatx' => 'pointsAtX',
        'pointsaty' => 'pointsAtY',
        'pointsatz' => 'pointsAtZ',
        'preservealpha' => 'preserveAlpha',
        'preserveaspectratio' => 'preserveAspectRatio',
        'primitiveunits' => 'primitiveUnits',
        'refx' => 'refX',
        'refy' => 'refY',
        'repeatcount' => 'repeatCount',
        'repeatdur' => 'repeatDur',
        'requiredextensions' => 'requiredExtensions',
        'requiredfeatures' => 'requiredFeatures',
        'specularconstant' => 'specularConstant',
        'specularexponent' => 'specularExponent',
        'spreadmethod' => 'spreadMethod',
        'startoffset' => 'startOffset',
        'stddeviation' => 'stdDeviation',
        'stitchtiles' => 'stitchTiles',
        'surfacescale' => 'surfaceScale',
        'systemlanguage' => 'systemLanguage',
        'tablevalues' => 'tableValues',
        'targetx' => 'targetX',
        'targety' => 'targetY',
        'textlength' => 'textLength',
        'viewbox' => 'viewBox',
        'viewtarget' => 'viewTarget',
        'xchannelselector' => 'xChannelSelector',
        'ychannelselector' => 'yChannelSelector',
        'zoomandpan' => 'zoomAndPan',
    );

    /**
     * Some SVG elements are case sensitive.
     * This map contains these.
     *
     * The map contains key/value store of the name is lowercase as the keys and
     * the correct casing as the value.
     */
    public static $svgCaseSensitiveElementMap = array(
        'altglyph' => 'altGlyph',
        'altglyphdef' => 'altGlyphDef',
        'altglyphitem' => 'altGlyphItem',
        'animatecolor' => 'animateColor',
        'animatemotion' => 'animateMotion',
        'animatetransform' => 'animateTransform',
        'clippath' => 'clipPath',
        'feblend' => 'feBlend',
        'fecolormatrix' => 'feColorMatrix',
        'fecomponenttransfer' => 'feComponentTransfer',
        'fecomposite' => 'feComposite',
        'feconvolvematrix' => 'feConvolveMatrix',
        'fediffuselighting' => 'feDiffuseLighting',
        'fedisplacementmap' => 'feDisplacementMap',
        'fedistantlight' => 'feDistantLight',
        'feflood' => 'feFlood',
        'fefunca' => 'feFuncA',
        'fefuncb' => 'feFuncB',
        'fefuncg' => 'feFuncG',
        'fefuncr' => 'feFuncR',
        'fegaussianblur' => 'feGaussianBlur',
        'feimage' => 'feImage',
        'femerge' => 'feMerge',
        'femergenode' => 'feMergeNode',
        'femorphology' => 'feMorphology',
        'feoffset' => 'feOffset',
        'fepointlight' => 'fePointLight',
        'fespecularlighting' => 'feSpecularLighting',
        'fespotlight' => 'feSpotLight',
        'fetile' => 'feTile',
        'feturbulence' => 'feTurbulence',
        'foreignobject' => 'foreignObject',
        'glyphref' => 'glyphRef',
        'lineargradient' => 'linearGradient',
        'radialgradient' => 'radialGradient',
        'textpath' => 'textPath',
    );

    /**
     * Check whether the given element meets the given criterion.
     *
     * Example:
     *
     * Elements::isA('script', Elements::TEXT_RAW); // Returns true.
     *
     * Elements::isA('script', Elements::TEXT_RCDATA); // Returns false.
     *
     * @param string $name The element name.
     * @param int    $mask One of the constants on this class.
     *
     * @return bool true if the element matches the mask, false otherwise.
     */
    public static function isA($name, $mask)
    {
        return (static::element($name) & $mask) === $mask;
    }

    /**
     * Test if an element is a valid html5 element.
     *
     * @param string $name The name of the element.
     *
     * @return bool true if a html5 element and false otherwise.
     */
    public static function isHtml5Element($name)
    {
        // html5 element names are case insensitive. Forcing lowercase for the check.
        // Do we need this check or will all data passed here already be lowercase?
        return isset(static::$html5[strtolower($name)]);
    }

    /**
     * Test if an element name is a valid MathML presentation element.
     *
     * @param string $name The name of the element.
     *
     * @return bool true if a MathML name and false otherwise.
     */
    public static function isMathMLElement($name)
    {
        // MathML is case-sensitive unlike html5 elements.
        return isset(static::$mathml[$name]);
    }

    /**
     * Test if an element is a valid SVG element.
     *
     * @param string $name The name of the element.
     *
     * @return bool true if a SVG element and false otherise.
     */
    public static function isSvgElement($name)
    {
        // SVG is case-sensitive unlike html5 elements.
        return isset(static::$svg[$name]);
    }

    /**
     * Is an element name valid in an html5 document.
     * This includes html5 elements along with other allowed embedded content
     * such as svg and mathml.
     *
     * @param string $name The name of the element.
     *
     * @return bool true if valid and false otherwise.
     */
    public static function isElement($name)
    {
        return static::isHtml5Element($name) || static::isMathMLElement($name) || static::isSvgElement($name);
    }

    /**
     * Get the element mask for the given element name.
     *
     * @param string $name The name of the element.
     *
     * @return int the element mask.
     */
    public static function element($name)
    {
        if (isset(static::$html5[$name])) {
            return static::$html5[$name];
        }
        if (isset(static::$svg[$name])) {
            return static::$svg[$name];
        }
        if (isset(static::$mathml[$name])) {
            return static::$mathml[$name];
        }

        return 0;
    }

    /**
     * Normalize a SVG element name to its proper case and form.
     *
     * @param string $name The name of the element.
     *
     * @return string the normalized form of the element name.
     */
    public static function normalizeSvgElement($name)
    {
        $name = strtolower($name);
        if (isset(static::$svgCaseSensitiveElementMap[$name])) {
            $name = static::$svgCaseSensitiveElementMap[$name];
        }

        return $name;
    }

    /**
     * Normalize a SVG attribute name to its proper case and form.
     *
     * @param string $name The name of the attribute.
     *
     * @return string The normalized form of the attribute name.
     */
    public static function normalizeSvgAttribute($name)
    {
        $name = strtolower($name);
        if (isset(static::$svgCaseSensitiveAttributeMap[$name])) {
            $name = static::$svgCaseSensitiveAttributeMap[$name];
        }

        return $name;
    }

    /**
     * Normalize a MathML attribute name to its proper case and form.
     * Note, all MathML element names are lowercase.
     *
     * @param string $name The name of the attribute.
     *
     * @return string The normalized form of the attribute name.
     */
    public static function normalizeMathMlAttribute($name)
    {
        $name = strtolower($name);

        // Only one attribute has a mixed case form for MathML.
        if ('definitionurl' === $name) {
            $name = 'definitionURL';
        }

        return $name;
    }
}